blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
ceff26dafa21c28c83de4b79f60fe60ac6cd70de | jamesbarone/ebay_app | /get_UPC.py | 482 | 3.71875 | 4 | '''The get UPC module contains the get_UPC function, which gets input from the user in the form of a
UPC. '''
def get_UPC():
'''Gets a UPC from the user, which will be used to guide the product search.
'''
user_UPC = input(
'Please enter the keyword of the product you would like to search for and press \'enter\' when finished! \n'
'Note that the more specifc the product, the better the search results')
return user_UPC
|
574895622999fa9470edeaab188cd25061e3806b | Brian-Mascitello/Advent-of-Code | /Advent of Code 2021/Day 3 2021/Day3Q2 2021.py | 1,473 | 3.578125 | 4 | """
Author: Brian Mascitello
Date: 12/5/2021
Websites: https://adventofcode.com/2021/day/3
Info: --- Day 3: Binary Diagnostic ---
--- Part Two ---
"""
import pandas as pd
def df_to_int(df):
df = df.astype(str)
df['String'] = df.apply(''.join, axis=1)
return_str = df['String'].iloc[0]
return_int = int(return_str, base=2)
return return_int
def filter_df(df, least_common=False):
variable = (1, 0)
if least_common:
variable = (0, 1)
start = 0
while len(df.index) >= 2:
df_column_sum = df[start].sum(axis=0)
if df_column_sum >= len(df.index) / 2:
df = df[df[start] == variable[0]]
else:
df = df[df[start] == variable[1]]
start = start + 1
return df
def prep_df():
df = pd.read_csv('Day3Q1 2021 Input.txt', names=['Original Binary'], dtype=str)
df = df['Original Binary'].str.split('', expand=True)
df = df.shift(periods=-1, axis='columns')
df = df.drop(df.columns[-2:], axis=1)
df = df.astype(int)
return df
def main():
df = prep_df()
df = filter_df(df)
oxygen_generator_rating = df_to_int(df)
df2 = prep_df()
df2 = filter_df(df2, least_common=True)
co2_scrubber_rating = df_to_int(df2)
print(f'oxygen_generator_rating: {oxygen_generator_rating}')
print(f'co2_scrubber_rating: {co2_scrubber_rating}')
print(f'multiply: {oxygen_generator_rating * co2_scrubber_rating}')
main()
|
f8b449a31b31dda38c68fd4cc426fd53ece2eb97 | yugwas/python-functions-worksheet | /lessons/03_say_hello/say_hello.py | 257 | 3.71875 | 4 | #Line 2 DEFINES the function say_hello()
def say_hello(name):
print("Hello " + name)
#Line 6 CALLS the function and PASSES in the ARGUMENT "AL" to a LOCAL VARIABLE name. VARIABLES that have ARGUMENTS assigned to them are called PARAMETERS
say_hello("Al") |
253cce6a2840008dd615ede3408ddd16df616030 | vaibhav5219/Tic-Tac-Toe | /Tic Tack Toe.py | 2,269 | 3.828125 | 4 | from introduction import intro
import os
intro()
print("Enter 1st player name :- ")
p1=input()
print("Enter 2nd player name :- ")
p2=input()
cross="X"
circle="O"
a=[""," "," "," "," "," "," "," "," "," "]
def print_table(n):
os.system("cls")
print("\t WELCOME TO ... TIC TAC TOE ...\n")
print(" | | ")
print(" ",a[1]," | ",a[2]," | ",a[3]," ")
print("______|______|______")
print(" | | ")
print(" ",a[4]," | ",a[5]," | ",a[6]," ")
print("______|______|______")
print(" | | ")
print(" ",a[7]," | ",a[8]," | ",a[9]," ")
print(" | | ")
def win_pos():
if(a[5]!=" "):
if(a[5]==a[1] and a[5]==a[9] or a[5]==a[3] and a[5]==a[7]):
if a[5]=="X":
return(1)
else:
return(0)
if(a[5]==a[2] and a[2]==a[8] or a[5]==a[4] and a[4]==a[6]):
if a[5]=="X":
return(1)
else:
return(0)
if(a[1]!=" "):
if(a[1]==a[4] and a[4]==a[7] or a[1]==a[2] and a[2]==a[3]):
if a[1]=="X":
return(1)
else:
return(0)
if(a[9]!=" "):
if(a[9]==a[6] and a[3]==a[9] or (a[9]==a[8] and a[8]==a[7]) ):
if a[9]=="X":
return(1)
else:
return(0)
for i in range(1,12):
if(i%2==0):
print(p2," turn ")
n=int(input())
if(a[n]!=" "):
print("You have entered wrong number")
break
a[n]=circle
print_table(n)
w=win_pos()
if w==1:
print(p1," wins")
break
elif (w==0):
print(p2," player wins")
break
else:
print(p1," turn ")
n=int(input())
if(a[n]!=" "):
print("You have entered wrong number")
break
a[n]=cross
print_table(n)
w=win_pos()
if w==1:
print("\n CONGRATULATIONS! Player",p1," wins")
break
elif w==0:
print("\n CONGRATULATIONS! ",p2, "player wins")
break
if(i==10):
print(" OOO Match Draw OOO")
break
input()
|
ba293a3960ba5ea08e2f661ba42d96845fc1f5e4 | nicefuu/leetCode-python3 | /int0804.py | 1,057 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/4/26 1:16
# @Author : Fhh
# @File : int0804.py
# Good good study,day day up!
"""
ๅน้ใ็ผๅไธ็งๆนๆณ๏ผ่ฟๅๆ้ๅ็ๆๆๅญ้ใ้ๅไธญไธๅ
ๅซ้ๅค็ๅ
็ด ใ
่ฏดๆ๏ผ่งฃ้ไธ่ฝๅ
ๅซ้ๅค็ๅญ้ใ
็คบไพ:
่พๅ
ฅ๏ผ nums = [1,2,3]
่พๅบ๏ผ
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]"""
from typing import List
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
if not nums:
return [[]]
nums.sort()
res = []
def mi(tmp, n, arr):
if len(tmp) == n:
res.append(tmp)
return
else:
for i in range(len(arr)):
if (not tmp or arr[i]>=tmp[-1]) and(i==0 or (i>0 and arr[i]>arr[i-1])):
mi(tmp + [arr[i]], n, arr[:i] + arr[i + 1:])
for i in range(len(nums)+1):
mi([], i, nums)
return res
s=Solution()
print(s.subsets([1,1,2,3])) |
60c83d0b6259823577e11c545825211e26fc9e29 | pauloMateos95/python_basico | /conversor_avanzado.py | 791 | 3.78125 | 4 | menu = """
Bienvenido al conversor de monedas
1- Pesos colombianos
2- Pesos argentinos
3- Pesos mexicanos
Elige una opciรณn """
opcion = input(menu)
def conversor(tipo_peso):
if tipo_peso == 'colombianos':
valor_dolar = 3875
elif tipo_peso == 'argentinos':
valor_dolar = 65
elif tipo_peso == 'mexicanos':
valor_dolar = 20
else:
return print('Ingresa una opciรณn valida')
pesos = float(input(f"ยฟCuรกntos pesos {tipo_peso} tienes?: "))
dolares = pesos / valor_dolar
dolares = round(dolares, 2)
print(f"Tienes ${dolares} dolares")
if opcion == '1':
conversor('colombianos')
elif opcion == '2':
conversor('argentinos')
elif opcion == '3':
conversor('mexicanos')
else:
print('Ingrese una opciรณn valida') |
0d0510d5c0b474ca793ce8f9010a65f405dad5cb | 10mincode/10mincode | /dicerollingsimultar.py | 483 | 4.0625 | 4 | import random
print("Welcome to dice rolling simultar")
input("Press Enter to continue")
p1name=input("Enter Player 1 Name: ")
p2name=input("Enter Player 2 Name: ")
print(f"Rolling rice for {p1name}...")
p1=random.randint(1,6)
print(p1)
input(f"Press Enter to roll dice for {p2name}")
print(f"Rolling rice for {p2name}...")
p2=random.randint(1,6)
print(p2)
if p1>p2:
print(f"{p1name} won")
elif p1==p2:
print("It's a draw")
else:
print(f"{p2name} won") |
94dd8286e5050f4c25ed4f3f8662fc25b0061888 | mblaszkiewicz/clouds-url-shortener | /url-shortener/db_urls.py | 1,419 | 3.515625 | 4 | class Database:
def __init__(self):
self.url_mappings = {}
self.id = 0
def delete_mappings(self):
"""Deletes all mappings stored in the memory"""
self.url_mappings.clear()
self.id = 0
def delete_mapping(self, idx):
"""Deletes single mapping identified by the ID (parameter)"""
self.url_mappings.pop(idx)
def add_mapping(self, url):
"""Adds a new URL to the data set, assigning first consecutive unassigned integer as the ID. If URL already
exists, throws Exception.
Function returns assigned ID and increments the counter used to track assigned IDs"""
if url in self.url_mappings.values():
raise Exception("Mapping already exists")
self.url_mappings[self.id] = url
self.id += 1
return self.id - 1
def get_url_id(self, url):
"""Returns ID for a given URL. If URL does not exist in the dictionary, function raises ValueError """
if url not in self.url_mappings.values():
raise ValueError()
return [k for k, v in self.url_mappings.items() if v == url][0]
def get_mapping(self, idx):
"""Returns actual URL for a given ID"""
return self.url_mappings[idx]
def get_mappings(self):
"""Returns the dictionary of mappings between IDs (elements of short URLs) and actual URLs"""
return self.url_mappings
|
83793434f353641a72ffd21b3b14168d3fa4343a | dewmanpower/Dewman | /ex7.py | 162 | 3.59375 | 4 | "https://www.practicepython.org/exercise/2014/03/19/07-list-comprehensions.html"
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print([ i for i in a if i%2 == 0])
|
a322a6c261c2b80b9c0e161d3b104e252d1c3014 | dikaa7/kripto4 | /rsa.py | 792 | 3.65625 | 4 | import random
from util import is_prime, gcd, modinv
def generate_keypair(p, q):
if not (is_prime(p) and is_prime(q)):
raise ValueError('Both numbers must be prime.')
elif p == q:
raise ValueError('p and q cannot be equal')
n = p * q
phi = (p-1) * (q-1)
e = random.randrange(1, phi)
g = gcd(e, phi)
while g != 1:
e = random.randrange(1, phi)
g = gcd(e, phi)
d = modinv(e, phi)
#Public key is (e, n) and private key is (d, n)
return ((e, n), (d, n))
def rsa_encrypt(pk, plaintext):
key, n = pk
cipher = [(ord(char) ** key) % n for char in plaintext]
return cipher
def rsa_decrypt(pk, ciphertext):
key, n = pk
plain = [chr((char ** key) % n) for char in ciphertext]
return ''.join(plain) |
d7898393dd7aa1bf25e7771fdc30c1632cd5f2e5 | Hello-Raviraj/Python-Programs | /Palidrome.py | 236 | 3.9375 | 4 | x="hello"
x.casefold()
y=reversed(x) #reversed function return reverse object
if list(x)==list(y): #so for comparision we convert them into list and then compare
print("its palindrome")
else:
print("no palindrome")
|
51cb575335bad84500d858cde3afb2e769792c6c | MahirRatanpara/pythonLearn | /14_mathFunctions.py | 358 | 3.921875 | 4 | import math
# there are various mathematical function present in the math module
# which helps us perform various complex math operation
x = 2.9
# round off the above number
y = round(x)
print(y)
x = -13
# abs return the mod value of our variable
y = abs(x)
print(y)
# trying few methods from math module
x = 3.6
print(math.ceil(x))
print(math.floor(x))
|
95630267a55a46d7774e5103f337f229df517829 | MaPing01/Python100 | /34.py | 588 | 3.921875 | 4 | #!usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Ma Ping
class A():
def __init__(self):
self.name = 'Aname'
def go(self):
print('a go a')
class B():
def go(self):
#super(B, self).go()
print('b go b')
class C(A):
def go(self):
super(C, self).go() #python2 and python3
print('c go c')
class D(B,A):
def __init__(self):
super(D, self).__init__()
self.age = 'Dage'
def go(self):
super().go() #python3
print('d go d')
#b = B()
d = D()
#b.go()
d.go()
print(d.name,d.age) |
0025e3166ed1629381c1f4b44b80f341ad4fa8c3 | jarvis-1805/DSAwithPYTHON | /Stacks and Queues/Queues/Reverse_Queue.py | 2,129 | 4.125 | 4 | '''
Reverse Queue
You have been given a queue that can store integers as the data. You are required to write a function that reverses the populated queue itself without using any other data structures.
Input Format:
The first list of input contains an integer 't' denoting the number of test cases/queries to be run.
Then the test cases follow.
The first line input for each test case/query contains an integer N, denoting the total number of elements in the queue.
The second line of input contains N integers separated by a single space, representing the order in which the elements are enqueued into the queue.
Output Format:
For each test case/query, the only line of output prints the order in which the queue elements are dequeued, all of them separated by a single space.
Output for every test case/query will be printed on a new line.
Note:
You are not required to print the expected output explicitly, it has already been taken care of. Just make the changes in the input queue itself.
Constraints:
1 <= t <= 100
1 <= N <= 10^4
-2^31 <= data <= 2^31 - 1
Time Limit: 1sec
Sample Input 1:
1
6
1 2 3 4 5 10
Note:
Here, 1 is at the front and 10 is at the rear of the queue.
Sample Output 1:
10 5 4 3 2 1
Sample Input 2:
2
5
2 8 15 1 10
3
10 20 30
Sample Output 2:
10 1 15 8 2
30 20 10
'''
from sys import stdin, setrecursionlimit
import queue
setrecursionlimit(10 ** 6)
def reverseQueue(Queue) :
# Your code goes here
Stack = []
while (not Queue.empty()):
Stack.append(Queue.queue[0])
Queue.get()
while (len(Stack) != 0):
Queue.put(Stack[-1])
Stack.pop()
return Queue
'''-------------- Utility Functions --------------'''
def takeInput():
n = int(stdin.readline().strip())
qu = queue.Queue()
values = list(map(int, stdin.readline().strip().split()))
for i in range(n) :
qu.put(values[i])
return qu
#main
t = int(stdin.readline().strip())
while t > 0 :
qu = takeInput()
reverseQueue(qu)
while not qu.empty() :
print(qu.get(), end = " ")
print()
t -= 1 |
b3a0b8cc2bd342ae79efaf11985c62de6e664aa1 | pramnora/python | /language/data/complex/list/array02.py | 823 | 4.625 | 5 | # python arrays can store mixed data types, including: number/string/numeric expression/
# and, even, include other sub-arrays, as well
num = [1,"111+111",111+111,"one",[1,2,3]]
for eachArrayItemNo in num:
print eachArrayItemNo
# python arrays can be searched using a specific array 'index number';
# the number count starts at: 0/and, ends at array last item number-1;
# in this case, the first array index data item number [0] stores a: 1
print num[0]
# this is how one indexes an array stored inside of an array by using 2 separate index numbers
# the first number refers to where inside the 'outer array' the 'inner array' item is stored;
# the second number refers to which particular array item we wish to select from the 'inner array': in this case, 2
print num[4][1]
#1
#111+111
#222
#one
#[1,2,3]
#1
#2
|
eaf677cc3a1e027c96f5ec68af817bdde7e0bf0f | Prins-Butt/uni-pro-troubles | /task4.py | 278 | 4.125 | 4 | def displayLargest(num1, num2):
if num1 > num2:
print("The first number is larger")
elif num2 > num1:
print("The second number is larger")
else:
print("Both numbers are equal")
displayLargest(7, 5)
displayLargest(1, 3)
displayLargest(4, 4)
|
785f7dfc15f43c438f645f638f4907dfc0936d3f | masoom-A/Python-codes-for-Beginners | /product odd even.py | 188 | 4.09375 | 4 | ## a=int(input('enter a number'))
for x in range (1,5,1):
p=x**2
if p%2==0:
print (x)
else:
print ('' "is a odd number",x)
|
484f48e2d0250c014a1f7d10229042c84d46e818 | fentonmartin/sample-python | /v-class 1 Post-test.py | 616 | 3.78125 | 4 |
x = (1,2,3)
print len(x)
for y in x:
print y,
'''a=10
b=5
d=0
if a and b or c or not d:
print abs(b-a)
'''
'''
x=3
if x == 0:
print x-3
elif x == 1 or x == 2:
print x
else:
print x-3*2
'''
'''
x = (1,2,3)
print len(x)
for y in x:
print y,
x[2]=4,
'''
'''n=5
while n<9:
print n
n=n+1,
'''
'''
a=['satu','dua','tiga','empat']
for i in range(len(a)):
print i,
'''
'''
a = 1
b = 2
c = a + b
s = str(a) + " + " + str(b) + " = " + str(c)
print s'''
'''colors = set(['red', 'green', 'blue'])
colors.add('yellow')
for color in colors:
print color,
'''
|
f0c614d588b64c749ce9fecbb845f1912042cc1f | RajibDasBhagat/Basic-programs-python | /convertToBin.py | 658 | 3.609375 | 4 | class stack:
def __init__(self):
self.items=[]
def push(self,item):
return self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def isEmpty(self):
return self.items == []
def size(self):
return len(self.items)
def divideBy2(decNum,base):
s=stack()
while(decNum > 0):
rem = decNum % base
s.push(rem)
decNum=decNum/base
binstring=" "
while not s.isEmpty():
binstring=binstring+str(s.pop())
return binstring
print(divideBy2(26,26)) |
9262ec198c6a986f9cb87bf86202d71f92d7e244 | teethzp/temp | /code1/totalinfo.py | 493 | 3.6875 | 4 | import sys,socket
def getipaddrs(hostname):
"""Given a host name,perform a standard (forward) lookup and return a list of IP addresses for
that host."""
result=socket.getaddrinfo(hostname,None,0,socket.SOCK_STREAM)
return [x[4][0] for x in result]
hostname=socket.gethostname()
print "Host name:",hostname
print "Fully-qualified name:",socket.getfqdn(hostname)
try:
print "IP address:", ", ".join(getipaddrs(hostname))
except socket.gaierror,e:
print "Couldn't get IP addresses:",e
|
65c991247455a58ea6ceb899109e5d5a19d71b92 | Komal97/DS-Algortihms | /13. Binary Search Tree/Python/No_of_unique_bst.py | 1,585 | 4 | 4 | '''
https://practice.geeksforgeeks.org/problems/unique-bsts/0
Find number of unique BST's with N nodes and nodes are numbered from 1 to N
This can be find out using catalan's number
'''
# using recursion
def find_catalan(num):
if num == 0:
return 1
ans = 0
for i in range(1, num+1):
ans += find_catalan(i-1)*find_catalan(num-i)
return ans
# using memoization
dp = [0]*100
def find_catalan_memoization(num):
if num == 0:
return 1
# if catalan of number is already computed
if dp[num] != 0:
return dp[num]
ans = 0
for i in range(1, num+1):
ans += find_catalan(i-1)*find_catalan(num-i)
# if catalan of number is computed first time
dp[num] = ans
return ans
# using formula - 2nCn/(n+1)
def factorial(n):
if n==0 or n==1:
return 1
prod = 1
for i in range(1, n+1):
prod *= i
return prod
def catalan_using_formula(num):
numerator = factorial(2*num)//(factorial(num)*factorial(num))
denominator = num+1
return numerator//denominator
if __name__ == '__main__':
for i in range(6):
print(find_catalan(i), end = ", ")
print()
for i in range(6):
print(find_catalan_memoization(i), end = ", ")
print()
for i in range(6):
print(catalan_using_formula(i), end = ", ")
# using tabulation
# if n=4, C0*C3 + C1*C2 + C2*C1 + C3*C0
n = int(input())
dp = [0]*(n+1)
dp[0] = 1
dp[1] = 1
for i in range(2, n+1):
for j in range(i):
dp[i] += (dp[j]*dp[i-j-1])
print(dp[n]) |
764a8150c8e4811c1c14ccfff0a1a14b5bdb81ee | CueOminousMusic/LaunchCode | /Project_Requirements.py | 4,798 | 3.5625 | 4 | Project Overview
The capstone project is one of the most important pieces of landing the perfect LaunchCode apprenticeship. This project will be one of the biggest ways that the LaunchCode evaluation team will verify that you're job-ready, and it should be something that you're proud to show off to a potential employer in an interview. So don't skimp on the time, energy, and thought that you put into this!
This is your opportunity to be unique, innovative and creative. This should be project that you conceived on your own and executed from start to finish. If you plan to use a project that you worked on with a group or at a bootcamp class, please come to the interview prepared to articulate the specific functions that you designed and programmed. We look for for projects that:
Demonstrate marketable skills: You have strong foundation in one of the languages from the skills milestone, and the related tools and best practices.
Demonstrate your ability to learn new things: You've gone beyond your initial learning to teach yourself something new. Maybe you learned Angular.js for your front-end web project, or customized the UI components of your mobile project.
Demonstrate utility for a company: In order to land that perfect job, a prospective employer will want to know that even as a relatively new programmer, you're capable of creating high-quality work for them.
Put your project up in GitHub. This will make it accessible for others to view, and will show off all of hard work you put into it as you rack up commits!
Here are some project ideas, along with potential features to get you started. You don't have to choose one of these; in fact, if you have another idea that you're passionate about, go for it! These project ideas are meant to give you an idea of the type and scale of projects that LaunchCode is looking for, along with giving practical project ideas that any learner at this level can tackle.
Regardless of the project you tackle, your project should:
Build an application entirely yourself, or nearly so. If you use "starter code" or a group project, you need to go well beyond what's already there, and be able to clearly articulate what you built yourself versus what was built or provided by others.
Include 3-5 killer features. The example projects will give you an idea of what constitutes a solid feature. Adding a new button to your web project? Probably not significant to count as a feature. Adding user login to your project? Yep, that's great!
Your Front End Web Project
Your front-end web project should demonstrate all of the great skills that you've learned to-date, along with a few new ones that you'll learn along the way.
You likely haven't learned much about back-end programming, and that's okay. If your app needs to store data, you can use HTML5 Web Storage, or you can create a stateless project ( that is, one that loses its data when the page is refreshed).
If you are comfortable with a back-end language, feel free to set up a back-end for your project and connect it to a database, but keep the majority of your work focused on the front-end, as that's what you'll want to shine brightest.
Core objectives:
Create web pages
Required: HTML, Enhance with CSS
Build a great user interface (UI)
Required: CSS, Optional: Enhance with Bootstrap
Add functionality (i.e. 5 features)
Required: JavaScript, Optional: JQuery and/or AJAX
Enhance user experience (UX) with a front-end framework
Required: Use one of React.js, Ember.js, Angular.js
Project examples
E-commerce site: display products and enable purchase
Feature 1: user management (registration, login, etc.)
Feature 2: gallery of items (view and select items)
Feature 3: shopping cart (save items for later)
Feature 4: checkout (purchase saved items)
Feature 5: payment API
Map application: access map APIs and display areas of interest
Feature 1: map of the location (google Map API)
Feature 2: search interface for areas of interest (Yelp API, or FourSquare)
Feature 3: display areas of interest on map
Feature 4: display information about location on mouseover
Feature 5: provide directions from user location?
Calendar application: display an interactive calendar
Feature 1: user management (registration, login, etc.)
Feature 2: display calendar
Feature 3: display different calendar views
Feature 4: display user created events
Feature 5: save user calendars
Time Commitment
The time to complete your project will may vary quite a bit from our estimate of 150 hours. You should focus on making a great product, and on hitting the objects listed above. In addition, as you go through the LaunchCode application process, our evaluation team may have some suggestions on how to make your project even better. |
35fca92096e19c8ab4adc30f8c17c235e7500615 | stuf/pyles | /pyles/_argparse.py | 828 | 3.59375 | 4 | """Provide argument parsing."""
import sys
from argparse import ArgumentParser, FileType
parser = ArgumentParser(prog='pyles', description='Collect pyles of data!')
parser.add_argument('inpath',
type=str,
help='Path to directory to search through')
parser.add_argument('-e', '--exts',
type=str,
default=['jpg', 'png'],
nargs='*',
help='List of file formats to go through')
parser.add_argument('-o', '--outfile',
type=FileType('w'),
nargs='?',
default=sys.stdout,
help='Save result to the given path')
def get_arguments():
"""Get the parsed arguments which the program was called with."""
return parser.parse_args()
|
16074783ba5ecabe7dbc9092ba9ff3b35517183e | vugutsa/Password-locker | /user.py | 1,609 | 3.84375 | 4 | class User:
"""
Class that generates new instances of contacts
"""
user_list = [] # Empty user list
def __init__(self,user_name,password):
# docstring removed for simplicity
self.user_name = user_name
self.password = password
def save_user(self):
'''
save_user method saves user objects into user_list
'''
User.user_list.append(self)
def delete_user(self):
'''
delete_contact method deletes a saved user from the user_list
'''
User.user_list.remove(self)
@classmethod
def find_by_user_name(cls,user_name):
'''
Method that takes in user_name and returns a contact that matches that number.
Args:
user_name: User_name to search for
Returns :
User that matches the user_name.
'''
for user in cls.user_list:
if user.user_name == user_name:
return user
@classmethod
def user_exist(cls,user_name):
'''
Method that checks if a user exists from the user list.
Args:
user_name: Username to search if it exists
Returns :
Boolean: True or false depending if the user exists
'''
for user in cls.user_list:
if user.user_name == user_name:
return True
return False
@classmethod
def display_users(cls):
'''
method that returns the user list
'''
return cls.user_list |
ee9460306b755e0a3e6d1ad9fce997dd30b99ee3 | IronE-G-G/algorithm | /leetcode/101-200้ข/151reverseWordsInAString.py | 826 | 4.28125 | 4 | """
151 ็ฟป่ฝฌๅญ็ฌฆไธฒ้็ๅ่ฏ
็ปๅฎไธไธชๅญ็ฌฆไธฒ๏ผ้ไธช็ฟป่ฝฌๅญ็ฌฆไธฒไธญ็ๆฏไธชๅ่ฏใ
็คบไพ 1๏ผ
่พๅ
ฅ: "the sky is blue"
่พๅบ: "blue is sky the"
่ฏดๆ๏ผ
ๆ ็ฉบๆ ผๅญ็ฌฆๆๆไธไธชๅ่ฏใ
่พๅ
ฅๅญ็ฌฆไธฒๅฏไปฅๅจๅ้ขๆ่
ๅ้ขๅ
ๅซๅคไฝ็็ฉบๆ ผ๏ผไฝๆฏๅ่ฝฌๅ็ๅญ็ฌฆไธ่ฝๅ
ๆฌใ
ๅฆๆไธคไธชๅ่ฏ้ดๆๅคไฝ็็ฉบๆ ผ๏ผๅฐๅ่ฝฌๅๅ่ฏ้ด็็ฉบๆ ผๅๅฐๅฐๅชๅซไธไธชใ
ๆฅๆบ๏ผๅๆฃ๏ผLeetCode๏ผ
้พๆฅ๏ผhttps://leetcode-cn.com/problems/reverse-words-in-a-string
่ไฝๆๅฝ้ขๆฃ็ฝ็ปๆๆใๅไธ่ฝฌ่ฝฝ่ฏท่็ณปๅฎๆนๆๆ๏ผ้ๅไธ่ฝฌ่ฝฝ่ฏทๆณจๆๅบๅคใ
"""
class Solution:
def reverseWords(self, s: str) -> str:
"""
็ฟป่ฝฌๆฐ็ป๏ผๅ ้ค้ฆๅฐพ็ฉบๆ ผ๏ผ็ฟป่ฝฌๅ่ฏ
"""
s = s.split()
return ' '.join(s[::-1])
|
b60119b2eff862ee06dfa94fad9fb622f0433f9a | Gohos322/HW4 | /Required by Assignment/ms.py | 486 | 3.546875 | 4 | '''
Created on 12 gen 2019
@author: Lorenzo Guenci (Student ID 1532651)
'''
def read_file ():
f = open("<path_to_file>", "r")
i=0
n=""
m=""
for x in f:
if i==0:
n=x.replace("\n", "")
if i==1:
m=x.replace("\n", "")
i+=1
return n,m
if __name__ == '__main__':
n,a=read_file()
b=[]
for x in a.split():
b.append(int(x))
b.sort()
for i in b:
print(i, end=" ")
|
b510c067bdd922d49141362f43555112cd554e21 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_148/198.py | 749 | 3.734375 | 4 | import sys
from bisect import bisect_right
def find_le(a, x):
'Find rightmost value less than or equal to x'
#print x
#print a
i = bisect_right(a, x)
if i:
#print "Found"
del a[i-1]
return True
return False
numCases = input()
for case in range( 1, numCases + 1 ):
N, S = [ int(x) for x in raw_input().split() ]
Nums = [ int(x) for x in raw_input().split() ]
numDisks = 0
SortedNums = sorted( Nums )
while ( len( SortedNums ) > 0 ):
largest = SortedNums.pop()
#print largest
numDisks += 1
if ( len(SortedNums) > 0 ):
#print SortedNums
other = find_le(SortedNums, S - largest)
#print SortedNums
output = str( numDisks )
print 'Case #' + str( case ) + ': ' + str( output )
|
80f0ee2ba2ba77730ff1153576e451db527b3165 | cerebrovoice/cv-monorepo | /cerebrovoice/capture/prompts.py | 6,655 | 3.515625 | 4 | import argparse
import json
import os
from collections import deque
from datetime import datetime
from random import choice, sample
from time import time
import pygame
# PYGAME SETUP
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
done = False
# ARG PARSING
parser = argparse.ArgumentParser()
parser.add_argument(
'--csv',
type=str,
default='./outputs.csv',
help='Where to save the CSV file')
parser.add_argument(
'--delay',
type=int,
default=500,
help='milliseconds that word appears on screen (500-1000 recommended)')
args = parser.parse_args()
file = args.csv
delay = args.delay
newDelay = 50
if not (file and delay):
raise Exception("Missing required arguments. Run with '-h' for help")
# HELPER FUNCTIONS
def curr_ms():
"""Returns the current time as milliseconds since the epoch"""
return int(time() * 1000)
def nearest_nth(num, n):
"""Rounds a number to the nearest multiple of n"""
return round(num / n) * n
def pluralize(s, n):
"""Naively pluralizes a singlular word based on the quantity.
Dog, 0 => Dogs
Dog, 1 => Dog
Dog, 2 => Dogs
Glass, 2 => Glasses
Doesn't handle special cases, such as Goose -> Geese"""
if n == 1:
return s
if s.endswith('s'):
return s + 'es'
return s + 's'
def tap_to_start():
"""Tells the user how to proceed with the program"""
global FILE
j, limit, s = 0, 5, "Press ANY KEY {} {} To Start"
while limit > 0:
j = 0
screen.fill((255, 255, 255))
t = s.format(limit, pluralize("Time", limit))
text = font3.render(t, True, (0, 128, 0))
screen.blit(text, (300 - text.get_width() // 2, 200 - text.get_height() // 2))
pygame.display.flip()
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key < 300:
j = 1 # handles buggy keys that registers as two keypresses
FILE.write("SENTINEL,NONE,{}\n".format(int(curr_ms()) - GLOBALSTART))
break
limit -= j
def is_escape_condition(event):
return ((event.type == pygame.QUIT) or (
event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE))
def is_pause_condition(event, keys=None):
if keys is None:
keys = [32, 113, 266]
return event.type == pygame.KEYDOWN and event.key in keys
def is_skip_condition(event, keys=None):
if keys is None:
keys = [271]
return event.type == pygame.KEYDOWN and event.key in keys
def process_keypress(event):
"""Returns the string representation of the key pressed"""
if 256 <= event.key <= 265:
return str(event.key - 256)
elif event.key == 256 + 15:
return 'enter'
# CSV SETUP
path = file.replace(os.path.basename(file), "")
if not os.path.isdir(path):
os.makedirs(path)
FILE = open(file, 'w')
FILE.write('keyPressed,wordSaid,timeStamp\n')
# FONTS SETUP
R, G, B = 0, 128, 0 # text color (RGB-255)
font = pygame.font.SysFont("comicsansms", 2 * 72)
font2 = pygame.font.SysFont("comicsansms", 90)
font3 = pygame.font.SysFont("comicsansms", 50)
font4 = pygame.font.SysFont("comicsansms", 80)
text = font.render("", True, (R, G, B))
text2 = font.render("", True, (R, G, B))
text3 = font3.render("", True, (R, G, B))
text4 = font4.render("", True, (R, G, B))
# VOCABULARY SETUP
WORD_LIST = ["yes", "no", "up", "down", "left", "right", "on", "off", "stop", "go"]
if os.path.isfile("configuration.json"):
with open("configuration.json", 'r') as file:
config = json.load(file)
WORD_LIST = config['words']
SILENCE = ""
# WORDS QUEUE SETUP
ltext_queue = deque()
ltext = choice(WORD_LIST)
newl = set(WORD_LIST)
ltext_queue.append(sample(newl, 1)[0])
prevWord = ltext_queue[-1]
newl = set(WORD_LIST)
newl.discard(prevWord)
ltext_queue.append(sample(newl, 1)[0])
prevWord = ltext_queue[-1]
newl = set(WORD_LIST)
newl.discard(prevWord)
ltext_queue.append(sample(newl, 1)[0])
prevWord = ltext_queue[-1]
# GENERAL VARIABLES SETUP
display_flag = True
last = 0
pause = False
next_word = False
nlast = 0
keydown = None
GLOBALSTART = curr_ms()
# MAIN LOOP
tap_to_start()
while not done:
# Handle Keypress events
for event in pygame.event.get():
if is_escape_condition(event):
print("File saved to {}".format(args.csv))
done = True
if is_pause_condition(event):
pause = not pause
if is_skip_condition(event):
next_word = not next_word
# All other keypresses
if event.type == pygame.KEYDOWN:
keydown = process_keypress(event)
# Set up text for screen output
current = curr_ms() - GLOBALSTART
if current - last > delay or next_word:
last = current
display_flag = not display_flag
if display_flag:
# Get a non-repeating word from the queue
ltext = ltext_queue.popleft()
newl = set(WORD_LIST)
newl.discard(prevWord)
ltext_queue.append(sample(newl, 1)[0])
prevWord = ltext_queue[-1]
if pause:
text = font.render("PAUSE", True, (0, 128, 0))
else:
# Set various text to be shown on screen
text = font.render(ltext, True, (0, 128, 0))
text2 = font2.render(ltext_queue[0], True, (0, 60, 0))
text3 = font3.render(ltext_queue[1], True, (0, 0, 0))
time1 = datetime.fromtimestamp((curr_ms() - GLOBALSTART) / 1000).strftime('%M:%S')
text4 = font4.render(str(time1), True, (0, 0, 0))
next_word = False
else:
text = font.render(SILENCE, True, (0, 128, 0))
text2 = font.render(SILENCE, True, (0, 128, 0))
text3 = font3.render(SILENCE, True, (0, 0, 0))
# Write to CSV file after appropriate amount of time
ncurrent = nearest_nth(curr_ms() - GLOBALSTART, 50)
if ncurrent - nlast > newDelay:
nlast = ncurrent
if pause:
s = "PAUSE,PAUSE,{}\n".format(ncurrent)
else:
s = "{},{},{}\n".format(keydown, ltext, ncurrent)
FILE.write(s)
keydown = None
# Draw text to screen
screen.fill((255, 255, 255))
screen.blit(text, (320 - text.get_width() // 2, 200 - text.get_height() // 2))
screen.blit(text2, (320 - text2.get_width() // 2, 305 - text2.get_height() // 2))
screen.blit(text3, (320 - text3.get_width() // 2, 390 - text3.get_height() // 2))
screen.blit(text4, (10, 10))
pygame.display.flip()
clock.tick(60)
|
4e61f61d091bcd26efd5cb8e80ecbe21411ceae0 | j1fig/euler | /3/main.py | 946 | 3.90625 | 4 | import sys
import cProfile
arg = int(sys.argv[1])
def _generate_next_prime(last_prime):
nextPrime = last_prime + 1
while True:
testNumber = 2
while nextPrime % testNumber != 0:
testNumber += 1
if testNumber == nextPrime:
yield nextPrime
nextPrime += 1
def find_prime_factors(primes, number, result=[]):
found_factor = False
for factor in primes:
if number % factor == 0:
found_factor = True
gen = _generate_next_prime(primes[-1])
while not found_factor:
factor = gen.next()
primes.append(factor)
if number % factor == 0:
found_factor = True
number = number/factor
result.append(factor)
if number == 1:
return result
return find_prime_factors(primes, number, result)
def main():
prime_factors = find_prime_factors([2, 3], arg)
print prime_factors
cProfile.run('main()')
|
c08680de268ca310aea325d4861e353c72661c77 | Jonathas-coder/Python | /EX 60 COM FOR.py | 119 | 3.75 | 4 | n=int(input('Qual o fatorial: '))
fator=n
for c in range (n-1,0,-1):
fator*=c
print(f'Fatorial de {n} รฉ {fator}')
|
c3a98056d8267129bbd34889953aded0fe191d9d | diogogarbin/curso_python | /if_formatacao.py | 1,355 | 4.3125 | 4 | #!/usr/bin/python3
#ola = '''
#Sejam Bem Vindos
#'''
#print(ola)
#nome = input ('Digite seu nome: ')# A funรงรฃo imput pausa o script e esper interaรงรฃo do usuรกrio
#print(nome.lower()) #lower() deixa tudo em minรบsculo tittle() deixa em formato de tรญtuli e upper() tudo minรบsculi
#Exercรญcio Atribuir dois nรบmero em variรกveis diferentes, e imprimir a soma dos dois
#num1 = 1
#num2 = 2
#soma = nm_1 + nm_2
#print(soma)
#________________________________________________________________________________________
#Comando Type mostra o tipo do arquivo
# O input pega nรบmeros como se fossem string entรฃo precisa converter
#print("o primeiro numero: {} o segundo numero: {}".format(num1, num2)) printar variรกvel no meio da frase
#Exercรญcio Leia o nome do aluno, 2 notas e calcule a mรฉdia
falta = int(input("Digite o numero de faltas"))
nome = input('Digite o nome do aluno: ')
nt1 = int(input("digite a primeira nota: "))
nt2 = int(input("digite a segunda nota: "))
md = nt1 + nt2 / 2
if md >= 7 and falta <= 4:
print("Aprovado")
else:
print("reprovado")
#print ('A Mรฉdia do {} รฉ: {}'.format(nome.lower(), md) )
#[] -> lista ou array, para adicionar usa-se o metodo .append
#{} -> Dicionรกrio
# EX
# cadastr0 = {"nome":"daniel", "idade":24}
# para acessar -> cadastro ['nome']
#.strip -> retira espaรงo caso o usuรกrio digite |
9e76eaf601ba2dd9d57fdb82074b2ebc68cb1924 | kyungha47/python | /36. class_inheritance/method_overriding.py | 400 | 3.671875 | 4 | #method overriding : subclass์์ base class์ ๋ฉ์๋๋ฅผ ์๋ก์ ์
class Person:
def greeting(self):
print('hi')
class Student(Person):
def greeting(self):
super().greeting()
# base class์ ๋ฉ์๋ ํธ์ถํ์ฌ ์ค๋ณต์ค์
print('nice to meet you')
# ๊ธฐ๋ฅ์ ์ ์งํ๋ฉด์ ์ ๊ธฐ๋ฅ์ ์ถ๊ฐ
kyungha = Student()
kyungha.greeting() |
fba8cef6ba16f7c40024dee0bdc262e9273e7542 | LubosKolouch/adventofcode_2019 | /08/t8.py | 1,016 | 3.5625 | 4 | #! python3
# I could not come with anything better than np solution in Reddit, so took it as
# a learning material...
from pprint import pprint
import numpy as np
# remember - best to read, strip and reshape in one line
with open('input', 'r') as data:
data = np.array(list(data.read().strip())).reshape((-1, 6, 25))
# get the minimal layer for sum of zeros
# python always interates along axis 0
zeros_layer = min(data, key=lambda func:np.sum(func == '0'))
# it's not summing the numbers itself, but number of times the condition is true
# it build boolean array and then sums the Trues
print(np.sum(zeros_layer == '1') * np.sum(zeros_layer == '2'))
# initial result is the first layout
result = data[0]
for next_layer in data:
# if item is not 2, keep what is there, otherwise put what found in the new layer
result = np.where(result != '2', result, next_layer)
# replace for better readability
result = np.where(result == '1', 'โ', ' ')
for row in result: # Part 2
print(*row, sep='')
|
b6fe044dfdc91efcc2c2075ef103f2cfcb9e95b1 | ahnjongin/BOJ | /1934.py | 214 | 3.59375 | 4 | def gcd(A, B):
if (A%B) == 0:
return B
if B == 0:
return A
else:
return gcd(B, A%B)
T=int(input())
for i in range(T):
A,B= map(int, input().split())
print(int(A*B/gcd(A,B))) |
de01ddb5fa3e9d63a73cfa7f04ddfa65bcb8580f | ZimingGuo/MyNotes01 | /MyNotes_01/Step02/6-MySQL/day02_15/exercise01_register_login_edited.py | 1,561 | 3.625 | 4 | # author: Ziming Guo
# time: 2020/4/19
'''
ๆจกๆๆณจๅ็ปๅฝ
'''
import pymysql
# ่ฟๆฅๆฐๆฎๅบ
db = pymysql.connect(host='localhost',
port=3306,
user='root',
password='19971023gzm',
database='stu',
charset='utf8'
)
# ๅๅปบๆธธๆ
cur = db.cursor()
def register():
name = input("็จๆทๅ:")
password = input("ๅฏ็ :")
sql = "select * from user where name='%s'" % name
cur.execute(sql)
result = cur.fetchone() # ๅฆๆๆฒกๆ่ฟไธช็จๆทๅ็่ฏๅฐฑ่ฟๅ็ฉบ
if result:
return False
try:
sql = "insert into user (name,passwd) values (%s,%s);"
cur.execute(sql, [name, password])
db.commit()
return True
except:
db.rollback()
return False
def login():
name = input("็จๆทๅ:")
password = input("ๅฏ็ :")
sql = "select * from user where name='%s' and passwd='%s'"
cur.execute(sql)
result = cur.fetchone()
if result:
return True
while True:
print("1-ๆณจๅ or 2-็ปๅฝ")
cmd = input("่พๅ
ฅๅฝไปค:")
if cmd == '1':
# ๆง่กๆณจๅ
if register():
print("ๆณจๅๆๅ๏ผ")
else:
print("ๆณจๅๅคฑ่ดฅ๏ผ")
elif cmd == '2':
# ๆง่ก็ปๅฝ
if login():
print("็ปๅฝๆๅ๏ผ")
break
else:
print("็ปๅฝๅคฑ่ดฅ๏ผ")
else:
print("ๆ ๆญคๅ่ฝ")
# ๅ
ณ้ญ
cur.close()
db.close()
|
5a448b8a57d1003b1898e02aeb1751764d0180d3 | Vlek/Project-Euler | /48.py | 223 | 3.703125 | 4 | #Problem 48
def selfpower(to):
'''adds all of the self powers together up to to'''
return sum([ num**num for num in range(1, to + 1) ])
if __name__ == '__main__':
print(str(selfpower(1000))[-10:])
|
85e7c0f23a71e7e76892ea61f1c99f77f03a73cd | TiagoTitericz/chapter2-py4e | /Chapter9/exercise3.py | 702 | 3.96875 | 4 | '''Exercise 3: Write a program to read through a mail log, build a histogram using a dictionary to count how many messages have come from
each email address, and print the dictionary.
Enter file name: mbox-short.txt
{'[email protected]': 1, '[email protected]': 3,
'[email protected]': 5, '[email protected]': 1,
'[email protected]': 2, '[email protected]': 3,
'[email protected]': 4, '[email protected]': 1,
'[email protected]': 4, '[email protected]': 2,
'[email protected]': 1}'''
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
dct_day = dict()
for line in fhand:
line = line.split()
if len(line) == 0:
continue
if line[0]== 'From':
dct_day[line[1]] = dct_day.get(line[1], 0) + 1
print(dct_day)
|
fd9235cd1884516449e0f5842da8d93e7c427587 | mrgentle1/koss_algorithm | /๊ณผ์ /2์ฃผ์ฐจ/boj_1918.py | 1,025 | 3.546875 | 4 | import sys
input = sys.stdin.readline
class Stack:
def __init__(self):
self.st = []
def push(self, e):
self.st.append(e)
def pop(self):
rt = self.st[-1]
self.st = self.st[:-1]
return rt
def top(self):
return self.st[-1]
def empty(self):
return len(self.st) == 0
sik = input()[:-1]
st = Stack()
result = ''
for i in sik:
if i.isalpha():
result += i
else:
if i == '(':
st.push(i)
elif i == '*' or i == '/':
while not st.empty() and (st.top() == '*' or st.top() == '/'):
result += st.pop()
st.push(i)
elif i == '+' or i == '-':
while not st.empty() and st.top() != '(':
result += st.pop()
st.push(i)
elif i == ')':
while not st.empty() and st.top() != '(':
result += st.pop()
st.pop()
while not st.empty():
result += st.pop()
print(result)
|
d6a6c4db9b7aa991ecc0c7458b47681a92d984f1 | Thereodorex/skillsmart_algo | /Part1/Task5/Queue_stack.py | 1,590 | 4.125 | 4 | class Node:
def __init__(self,value):
self.value = value
self.next = None
class Stack:
'''
ะ ะตะฐะปะธะทะฐัะธั ััะตะบะฐ ะฝะฐ ัะฟะธัะบะต
'''
def __init__(self):
self.head = None
self._size = 0
def size(self):
return self._size
def pop(self):
'''
ะกะปะพะถะฝะพััั O(1)
'''
if self._size == 0:
return None
self._size -= 1
result = self.head.value
self.head = self.head.next
return result
def push(self, value):
'''
ะกะปะพะถะฝะพััั O(1)
'''
self._size += 1
node = Node(value)
node.next = self.head
self.head = node
def peek(self):
return self.head.value
class Queue:
'''
ะัะตัะตะดั ะฝะฐ ััะตะบะฐั
'''
def __init__(self):
self.stack_a = Stack()
self.stack_b = Stack()
self._size = 0
def enqueue(self, item):
'''
ะััะฐะฒะธัั ะฒ ะบะพะฝะตั
ะกะปะพะถะฝะพััั O(1)
'''
self._size += 1
self.stack_a.push(item)
def dequeue(self):
'''
ะะทััั ะธะท ะฝะฐัะฐะปะฐ
ะกะปะพะถะฝะพััั (ะฐะผะพััะธะทะธัะพะฒะฐะฝะฝะฐั) O(1)
'''
if self._size == 0:
return None
self._size -= 1
if not self.stack_b.size():
while self.stack_a.head is not None:
self.stack_b.push(self.stack_a.pop())
return self.stack_b.pop()
def size(self):
return self._size |
ada4239debbb5030bce6ea00d7182c638ccda05b | zhangmeilu/VIP8study | /ๆจๅฏผๅผ.py | 3,862 | 3.953125 | 4 | # ไฝ็จ๏ผ็จไธไธช่กจ่พพๅผๅๅปบไธไธชๆ่งๅพ็ๅ่กจๆๆงๅถไธไธชๆ่งๅพ็ๅ่กจ
# ๅ่กจๆจๅฏผๅผๅๅซๅ่กจ็ๆๅผ
# ้ๆฑ๏ผๅๅปบไธไธช0-10็ๅ่กจ
# whileๅพช็ฏๅฎ็ฐ
from homework import num
list1 = []
i = 0
while i < 10:
list1.append(i)
i += 1
print(list1)
# forๅพช็ฏๅฎ็ฐ
list1 = []
for i in range(10):
list1.append(i)
print(list1)
# ๅธฆif็ๅ่กจๆจๅฏผๅผ
# ้ๆฑ๏ผๅๅปบ0-10็ๅถๆฐๅ่กจ
# ๆนๆณไธ๏ผrange()ๆญฅ้ฟๅฎ็ฐ
list1 = [i for i in range(0,10,2)]
print(list1)
list2 = [i for i in range(1,10,2)]
print(list2)
# ๆนๆณ2๏ผifๅฎ็ฐ
list1 = [i for i in range(10) if i % 2 == 0]
print(list1)
list2 = [i for i in range(10) if i % 2 == 1]
print(list2)
# ๅคไธชforๅพช็ฏๅฎ็ฐๅ่กจๆจๅฏผๅผ
# ้ๆฑ๏ผๅๅปบๅ่กจๅฆไธ๏ผ
# [(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]
list1 = [(i,j) for i in range(1,3) for j in range(3)]
print(list1)
# ๅญๅ
ธๆจๅฏผๅผ
# ๆ่๏ผๅฆๆๆๅฆไธไธคไธชๅ่กจ๏ผ
# list1 = ['name','age','gender']
# list2 = ['Tom',20,'็ท']
# ๅฆไฝๅฟซ้ๅๅนถไธบไธไธชๅญๅ
ธ๏ผๅญๅ
ธๆจๅฏผๅผ
# ๅๅปบไธไธชๅญๅ
ธ๏ผๅญๅ
ธkeyๆฏ1-5ๆฐๅญ๏ผvalueๆฏ่ฟไธชๆฐๅญ็2ๆฌกๆน
dict1 = {i: i**2 for i in range(1,5)}
print(dict1)
# ๅฐไธคไธชๅ่กจๅๅนถไธบไธไธชๅญๅ
ธ
list1 = ['name','age','gender']
list2 = ['Tom',20,'็ท']
dict1 = {list1[i]: list2[i] for i in range(len(list2))}
print(dict1)
# ๆๅๅญๅ
ธไธญ็ฎๆ ๆฐๆฎ
counts = {'MBP': 268,'HP': 125,'DELL': 201,'Lenovo': 199,'acer': 99}
count1 = {key: value for key,value in counts.items() if value <= 200}
print(count1)
# ้ๅๆจๅฏผๅผ
# ้ๆฑ๏ผๅๅปบไธไธช้ๅ๏ผๆฐๆฎไธบไธๆนๅ่กจ็2ๆฌกๆน
# list1 = [1,1,2]
# set1 = {i ** 2 for i in list1}
# print(set1)
# password = input('่ฏท่พๅ
ฅๅฏ็ ๏ผ ')
# print(f'ๆจ่พๅ
ฅๅพๅฏ็ ๆฏ๏ผ{password}')
# print(type(password))
#
# num = input('่ฏทๆจ่พๅ
ฅๆจ็ๅนธ่ฟๆฐๅญ๏ผ')
# print(f"ๆจ็ๅนธ่ฟๆฐๅญๆฏ{num}")
# print(type(num))
# print(type(int(num)))
# mystr = "hello"
# print(mystr.split(' ',5))
# mystr = ['h','e','l','l','o']
# print(''.join(mystr))
mystr = "hello world and you"
print(mystr.lstrip('h'))
# list1 = [1,2,3,4,5,5,2,3,4,2,4]
# print(set(list1))
# ๆ่๏ผๅๅ
ฌไบค๏ผๅฆๆๆ้ฑๅฏไปฅไธโป๏ผๆฒก้ฑไธ่ฝไธโป๏ผไธโปๅๅฆๆๆ็ฉบๅบง๏ผๅๅฏไปฅๅไธ๏ผๅฆๆๆฒก็ฉบๅบง๏ผๅฐฑ่ฆ็ซ็ใๆไนไนฆๅ็จๅบ๏ผ
# money = 1่กจ็คบๆ้ฑ๏ผmoney = 0่กจ็คบๆฒก้ฑ
# seat = 0่กจ็คบๆฒกๅบง๏ผseat = 1 ่กจ็คบๆๅบง
# money = 1
# # seat = 0
# # input('่ฏทๆๅธ๏ผ')
# # input('ๆฏๅฆๆๅบงไฝ๏ผ ')
# # if money == 1:
# # print('่ฏทไธ่ฝฆ')
# # if seat == 1:
# # print('ๆ็ฉบไฝ๏ผ่ฏทๅ')
# # else:
# # print('่ฏท็ซ็จณๆถๅฅฝ')
# # else:
# # print('ไฝ้ขไธ่ถณ๏ผ่ฏทๅ
ๅผ๏ผไธๅพไธ่ฝฆ')
# money = 1
# seat = 0
# if money == 1:
# print('โผ่ฑช๏ผไธๅทฎ้ฑ๏ผ้กบๅฉไธโป')
# if seat == 1:
# print('ๆ็ฉบๅบง๏ผๅฏไปฅๅไธ')
# else:
# print('ๆฒกๆ็ฉบๅบง๏ผ็ซ็ญ')
# else:
# print('ๆฒก้ฑ๏ผไธ่ฝไธโป๏ผ่ฟฝ็ๅ
ฌไบคโป่ท')
# import random
# random.randint()
#
# a = 1
# b = 2
# c = a if a > b else b
# print(c)
# list1 = [i for i in range(100) if i % 3 == 0]
# print(list1)
# list1 = [i for i in range(0,100,3)]
# print(list1)
# list1 = [3,2,1,5,4,0,2]
# for i in list1:
# i = i ** 2
# print(list1)
# list1 = [3,2,1,5,4,0,2]
# set1 = {1 ** 2 for i in list1}
# print(set1)
#
# list1 = ['name']
# list2 = ['Tom']
# list3 = list1 + list2
# print(list3)
# print(dict{list3})
# 3 + 2 + 1
# def sum_numbers(num):
# if num == 1:
# return 1
# return num + sum_numbers(num - 1)
# sum_result = sum_numbers(4)
# print(sum_result)
# 1,1,2,3,5,8,11,19...
# def sum_numbers(num):
# if num == 1:
# return 1
# list1 = [1,2,3,4,5,5,2,3,2,4]
# print(set(list1))
# list1 = [i for i in range(100) if i % 3 == 0]
# print(list1)
|
0be5717ef766e8011878820b1fe3aa18590efb1a | shiyushui5/python_py | /y01083.py | 432 | 3.96875 | 4 | from y01083f import Answer_survey
question = "what language did you first to learn?"
my_survey = Answer_survey(question)
my_survey.show_question() #ๆพ็คบ้ฎ้ขๅนถๅญๅจ็ญๆก
print("Enter 'a' at any time to quit.\t")
while True:
response = input("language: ")
if response == 'a':
break
my_survey.store_response(response)
print("\tThank you to everyone who participated in the survey!")
my_survey.show_result()
|
e4492ad5cdd01de60b20e0786269ccc5350e0efb | yxserious/python_learning | /string.py | 608 | 3.6875 | 4 | name = 'steven'
result ='eve' in name
print(result)
#not in
result = 'tv' not in name
print(result)
#r ไฟ็ๅๆ ผๅผ ๆrๅฐฑไธ่ฝฌไน๏ผๆฒกๆrๅ่ฝฌไน
name = 'jason'
print(r'%s: \'hahaha!\''%name)
filename = 'picture.png'
print(filename[5]) #้ๅ
ฑใใ็ปๅไฝ็ฝฎ่ทๅๅญๆฏ๏ผๅช่ฝไธไธช
#ๅ
ๅไธๅ
ๅ
print(filename[0:7])#0123456
print(filename[3:])#็็ฅๅ้ขๅฐฑไธ็ดๅฐ็ปๅฐพ
print(filename[:7])#็็ฅๅ้ขๅฐฑๆฏไป0ๅผๅงๅ
#f i l e n a m e . p n g
#0 1 2 3 4 5 6 7 8 9 10 11
print(filename[8:-1])
#ไธ็ดๅฐn๏ผๆๅๆฐ็ฌฌไบไฝ
print(filename[:-2])
#ไธ็ดๅฐๅๆฐ็ฌฌไบไฝ
|
946d5e5bb9f91c240ba202dbaa26e0e8d31bb5fe | AdamZhouSE/pythonHomework | /Code/CodeRecords/2989/58575/252564.py | 264 | 4.03125 | 4 | str1=input()
str2=input()
str3=input()
if str1>str2:
temp=str1
str1=str2
str2=temp
if str3<str1:
print(str3,"\n",str1,"\n",str2,sep="")
elif str3<str2:
print(str1,"\n",str3,"\n",str2,sep="")
else:
print(str1,"\n",str2,"\n",str3,sep="")
|
6c630d9124b309ea802ca0288a6b3fbba18fcdc2 | feelthecoder/python_practice | /dict_sets_comprehension.py | 524 | 4.28125 | 4 | # Dictionary comprehension used to create dictionary in one line
square = {num:num**2 for num in range(1,11)} # Dictionary of key square
print(square)
#create a dictionary of character count of a string
String = "Vikas is a good programmer"
dict_count = {i:String.count(i) for i in String}
print(dict_count)
#dict comprehension with if else
odd_even = {i: ('even' if i%2==0 else 'odd') for i in range(1,11)}
print(odd_even)
# Set comprehension used to create set in one line
s= {k**2 for k in range(1,11)}
print(s) |
35a71f8822d4ea2036c2a6f4122c5298c2fb5ba5 | glambertation/ToGraduate | /Leetcode/python/coins/500/567.py | 1,387 | 3.734375 | 4 | '''
Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.
Example 1:
Input:s1 = "ab" s2 = "eidbaooo"
Output:True
Explanation: s2 contains one permutation of s1 ("ba").
Example 2:
Input:s1= "ab" s2 = "eidboaoo"
Output: False
'''
'''
tips ๆปๅจ็ชๅฃ
'''
v1
class Solution(object):
def checkInclusion(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
A = [ord(x) - ord('a') for x in s1]
B = [ord(x) - ord('a') for x in s2]
mp = [0]*26
for x in A:
mp[x] += 1
window = [0] * 26
for i, x in enumerate(B):
window[x] += 1
if i >= len(A):
window[B[i - len(s1)]] -= 1
if mp == window:
return True
return False
v2
class Solution(object):
def checkInclusion(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
c1, c2 = collections.Counter(s1), collections.Counter(s2[0:(len(s1)-1)])
for i in range(len(s2)-len(s1)+1):
c2[s2[i+len(s1)-1]] += 1
if not (c1 -c2):
return True
c2[s2[i]] -= 1
return False
|
64be083c8d5355b43b631efb0d4fe59caca265cc | Zhenye-Na/leetcode | /python/293.flip-game.py | 1,064 | 3.78125 | 4 | # [293] Flip Game
# Description
# You are playing the following Flip Game with your friend:
# Given a string that contains only two characters: `+` and `-`,
# you can flip two consecutive `"++"` into `"--"`, you can only flip one time.
# Please find all strings that can be obtained after one flip.
# Write a program to find all possible states of the string after one valid move.
# Example
# Example 1
# Input: s = "++++"
# Output:
# [
# "--++",
# "+--+",
# "++--"
# ]
# Example 2
# Input: s = "---+++-+++-+"
# Output:
# [
# "---+++-+---+",
# "---+++---+-+",
# "---+---+++-+",
# "-----+-+++-+"
# ]
class Solution:
"""
@param s: the given string
@return: all the possible states of the string after one valid move
"""
def generatePossibleNextMoves(self, s):
# write your code here
if not s or len(s) < 2:
return []
res = []
n = len(s)
for i in range(n - 1):
if s[i:i + 2] == "++":
res.append(s[:i] + "--" + s[i + 2:])
return res
|
943b197ff725026ba3c77de689df186f475d8bc0 | rkks/refer | /script-prog/python/Python-Prog-on-Win32/ch06_doubletalk/doubletalk/dictlist.py | 1,721 | 3.515625 | 4 | # dictionary queries
"""dictlist.py
Assume we have a list of dictionaries. This extracts tabular data
from them, and provides common operations useful on such a list
"""
import doubletalk.datastruct
def GetKeys(dictlist):
"lists all the keys in all the dictionaries"
s = doubletalk.datastruct.Set()
for dict in dictlist:
for key in dict.keys():
s.add(key)
return s.elements()
def Tabulate(dictlist, keylist=None):
"returns a tabular data set for given keys"
if keylist == None:
keylist = GetKeys(dictlist)
result = []
for dict in dictlist:
row = []
for key in keylist:
try:
row.append(dict[key])
except KeyError:
row.append(None)
result.append(tuple(row))
return result
def SelectHavingKey(dictlist, key):
"returns all dicts which have a certain key"
result = []
for dict in dictlist:
if dict.has_key(key):
result.append(dict)
return result
def SelectHavingKeyAndValue(dictlist, key, value):
"returns all dicts which have a certain key"
result = []
for dict in dictlist:
try:
if dict[key] == value:
result.append(dict)
except:
pass
return result
def MakeDictList(count=100):
"Makes some sample data"
from random import choice, random
Products = ['Widgets','Sprockets','Gaskets','Thingies','Wotsits']
Stores = ['Putney','Clapham','Wimbledon','Richmond','Fulham']
Months = [9801,9802,9803,9804,9805]
result = []
for i in range(count):
dict = {}
dict['Amount'] = int(1000 * random())
dict['Month'] = choice(Months)
dict['NominalAccount'] = 'Sales'
dict['Product'] = choice(Products)
dict['Store'] = choice(Stores)
result.append(dict)
return result
|
924c97c4403a8f8fe3d63e5c55e4fd9ece15e682 | uterdijon/evan_python_core | /_class_code/02_mammals.py | 1,903 | 4.1875 | 4 | class Animal(object):
"""docstring for Animal"""
body = True
def __init__(self):
self.substance = "carbon"
class Mammal(Animal):
"""
A clade of endothermic amniotes distinguished from reptiles
(including birds) by the possession of a neocortex (a region of the
brain), hair, three middle ear bones, and mammary glands.
Attributes:
glands (str): Description
way_of_moving (st): Description
Deleted Attributes:
hair (str): Description
"""
def __init__(self, animal_type, way_of_moving, color):
# the next two lines do the same (different syntax):
# calling the superclasses __init__ method
Animal.__init__(self)
# super(Mammal, self).__init__()
# ------------------------------------------------
# without the Animal init, self.body is still going to be available,
# however, self.substance is NOT going to be available
self.glands = "has glands" # this is inherent for a Mammal!
self.animal_type = animal_type
self.way_of_moving = way_of_moving
self.color = None
def move(self, distance):
"""
Moves the mammal by a certain distance.
Args:
distance (int): the distance in meters
Returns:
str: a sentence describing the mammal's movement
"""
return f"{self.animal_type} {self.way_of_moving}s {distance} meters"
def __str__(self):
return f"{self.animal_type} | {self.way_of_moving}"
class Whale(Mammal):
"""docstring for Whale"""
def __init__(self):
Mammal.__init__(self, "whale", "swim", "blue")
willy = Whale()
print(willy.body)
willy.move(30)
print(willy)
print(willy.__str__())
print(willy.__str__().__str__().__str__().__str__().__str__().__str__().__str__().__str__())
|
b15e2d2e4505c23ab001cb5e6ef2b61c3d24e1ab | Roshni-jha/ifelse | /nested if else-pyt/strong num.py | 105 | 3.75 | 4 | num=int(input("enter the number"))
i=0
while i<=100:
if i%1!=0 and i%2!=0:
print(i)
i=i+1 |
e4dadc4361c77eda4bde15a4828d37bc14712e3e | SaurabhPal25081995/Full-Python-Course | /Ex 5- Pattern Printing.py | 410 | 3.796875 | 4 | # Pattern is n = no. of rows
"""
*****
****
***
**
*
"""
row = int(input("Enter no. of rows "))
bol = input("Type 1 for True, 0 for False")
var = bool(bol)
print(bol)
if bol==True:
for i in range(0,row):
for j in range(0,i+1):
print("*",end=" ")
print("\r")
else:
for i in range(0, row):
for j in range(row, i, -1):
print("* ", end="")
print()
|
ea182e879f2e582b3cc0397ecc9425c0408d5b25 | zengm71/Dojo | /Python/Assignments/UserWithBankAccount/userWithBankAccount.py | 1,766 | 4.15625 | 4 | class BankAccount:
def __init__(self, int_rate, balance):# now our method has 2 parameters!
self.account_balance = balance # the account balance is set to $0, so no need for a third parameter
self.int_rate = int_rate
def deposit(self, amount):
self.account_balance += amount
return self
def withdrawal(self, amount):
self.account_balance -= amount
return self
def yield_interest(self):
self.account_balance *= (1 + self.int_rate)
return self
class User:
def __init__(self, username, email_address, int_rate, balance):# now our method has 2 parameters!
self.name = username # and we use the values passed in to set the name attribute
self.email = email_address # and the email attribute
self.account1 = BankAccount(int_rate, balance) # the account balance is set to $0, so no need for a third parameter
self.account2 = BankAccount(int_rate, balance) # the account balance is set to $0, so no need for a third parameter
def make_deposit(self, account, amount):
getattr(self, account).deposit(amount)
return self
def make_withdrawal(self, account, amount):
getattr(self, account).withdrawal(amount)
return self
def display_user_balance(self, account):
print(f"{self.name} with Email {self.email } now has a balance of {getattr(self, account).account_balance} in account1")
return self
def __str__(self):
return self.name
user1 = User(username='User1', email_address='[email protected]', int_rate=.05, balance=100)
user1.display_user_balance(account= 'account1')
user1.make_deposit(account = 'account1', amount = 100).display_user_balance('account1')
# print(user1)
|
cf84a06ed83c2aeada502e575156154f34d523c3 | trygvels/AST1100 | /Trygveoblig1.py | 2,400 | 4.125 | 4 | #Problem 7.2
#-------------------------Comments------------------------
"""
In this task we assume that since Beagles mass is so small
ralative to Mars, that Mars' velocity and position after
the initial values are negligible.
We are only looking at Beagles position and velocity,
using the velocity to calculate the position for the next
iteration.
To simplify the program i vectorized everything into the
vector u, witch contains both position and velocity,
iterating over it in the while loop, calculating the force
until the distance from origo is less than the radius of Mars,
which means that it has landed (or crashed).
"""
#-------------------------Imports---------------------------
from scitools.std import *
from numpy.linalg import norm
#-------------------------Defining variables-----------------
G = 6.67*10**-11 #Gravitational constant
k = 0.00016 #Friction constant
radius = 3400000 #Radius of Mars in meters
Mars_mass = 6.4*10**23 #[kg]
Beagle_mass = 100.0 #[kg]
u0 = asarray([[-298000 - radius, 0.0], [0.0, -4000]])
#position (x,y), Velocity (x,y)
u = zeros((70000, 2, 2)) #Empty array for values
u[0] = u0 #Adding initial values to u
n = 70000
i=0
land = 'no' #Beagle has not landed
#-------------------------Force function---------------------
def Force(u): #Both forces (Athmospheric friction and Gravitation)
r = u[0]
v = u[1]
a = -k*v/Beagle_mass - G*Mars_mass*r/(norm(r)**3)
return asarray([v, a])
#--------------------------While loop------------------------
while land=='no' and i<(n-1):
h = 100 # Calculating position and velocity (MidEuler)
u[i+1] = u[i] + h*Force(u[i] + h/2*Force(u[i])) # Timestep not needed
r = u[i+1] #Distance from (0,0)
if norm(r) < radius: #As explained; if it kicks in, we have landed
land = 'yes'
break
i = i+1
x = u[:,0][:,0]
y = u[:,0][:,1]
#-------------------------Plot command----------------------
t=linspace(0,2*pi, 70000) # Making an array for my simple Mars plot.
marsx=array(radius*cos(t))
marsy=array(radius*sin(t))
plot(x,y, '-b', marsx,marsy,'r',axis='equal') #Mars is the red circle (Not an orbit)
savefig('PlotOblig1.png')
"""
Problem 7.3
It looks as if Beagle lands on mars close to where it started after orbiting
mars 2 times.
"""
|
864b491f8e35abce206d69f229e2c0dbadc50f35 | Biddy79/eclipse_python | /OOP/Classes/__init__.py | 1,901 | 4.59375 | 5 | #first we must understand that in python underscores are used before the nameing of
#methods. They act just the same as methods/functions below is and example of this
a = 12
b = 4
print(a + b)
# __add__ is a function which works the same as the + operator take note of the dot
# notation before calling and () at the end which takes parameter .__add__()
print(a.__add__(b))
print('-' * 30)
#Classes are used to build a template of objects
#class name is dog and we pass objects as a parameter. dog(object)
#"__init__" is a reseved method in python classes.
#It is called as a constructor in object oriented terminology
#The self parameter is a reference to the current instance of the class,
#and is used to access instence variables that belongs to the class.
class dog(object):
def __init__(self, name, age):
self.name = name
self.age = age
self.vicious = False
#Adding new method to class dog
def attack(self):
self.vicious = True
#Instantiate and instance of dog. seting Rover = to template of dog()
#passing in values name and age
Rover = dog("Rover", 2)
#printing out return values of name and age from defiined obejct Rover
print(Rover.name)
print(Rover.age)
#now creating another instence of class dog
billy = dog("Billy", 11)
print(f"Dogs name is {billy.name} and he is {billy.age} years old")
print("-" * 30)
#printing vicious attribute set in constructor on line 28
print(billy.vicious)
#calling method attack on line 31 which changes attribute of vicious to True
billy.attack()
#printing out vicious after status being changed
print(billy.vicious)
print("-" * 30)
#We can also add instance variables to class from out side of initial definition
Rover.colour = "brown"
print(Rover.colour)
#Take note not ever instance of dog class will have attribute colour!!!
#Cannot do billy.colour !!!!!
|
8ccce9acb0afec392646c43ea685540a344d373b | tahsinozden/MyDevelopmentEnv | /CodeSnippets/Python/tests.py | 531 | 3.703125 | 4 | from unittest import TestCase
from main import Animal
class TestAnimal(TestCase):
def test_myName(self):
animal = Animal('tiger', 'predator')
self.assertEqual(animal.myType, 'My type is tiger')
def test_str_overloading(self):
animal = Animal('lion', 'king')
self.assertEqual('My type is lion and I am king', str(animal))
class TestGeneral(TestCase):
def test_ternary_conditional_opetator(self):
self.assertEqual("Greater", ("Greater" if 12 > 0 else "Smaller"))
|
49ddfefada05cdef9adf903730d629679e6d193a | trvsed/100-exercicios | /ex004.py | 394 | 3.8125 | 4 | var1 = input ('Digite algo: ')
print('O tipo primitivo desse valor รฉ',(type(var1)))
print('Sรณ tem espaรงos?',var1.isspace())
print('ร um nรบmero?',var1.isnumeric())
print('ร alfabรฉtico?',var1.isalpha())
print('ร alfanumรฉrico?',var1.isalnum())
print('Estรก em maiรบsculas?',var1.isupper())
print('Estรก em minรบsculas?',var1.islower())
print ('Estรก capitalizada?',var1.istitle()) |
d6f6c0c92a4350525cefab213576391d4c05e9c4 | Anjali-Poornima666/Passbook | /a.py | 603 | 3.53125 | 4 | import sys
import msvcrt
def win_getpass(prompt='Password: ', stream=None):
"""Prompt for password with echo off, using Windows getch()."""
import msvcrt
for c in prompt:
msvcrt.putch(c)
pw = ""
while 1:
c = msvcrt.getch()
if c == '\r' or c == '\n':
break
if c == '\003':
raise KeyboardInterrupt
if c == '\b':
pw = pw[:-1]
msvcrt.putch('\b')
else:
pw = pw + c
msvcrt.putch("*")
msvcrt.putch('\r')
msvcrt.putch('\n')
return pw
a=win_getpass()
print(a)
|
dc363a4634b61435e6a2d4cfed354b08b999a8c6 | varunchandan2/python | /vacationCost.py | 536 | 3.890625 | 4 | try:
user = int(input('Please enter a range of numbers in 4 to 16 weeks: '))
except:
print("ERROR! Please enter number")
else:
for num in range(1,17):
while user < 17:
if user >= 4 and user <= 6:
print("Rent cost: $3080")
elif user >= 7 and user <= 10:
print("Rent cost: $2650")
elif user >= 11 and user <= 16:
print("Rent cost: $2090")
else:
print("not in the range")
|
3417c82809c064f521ca7b598607746d036b03ad | LXZbackend/Base_python | /0815/NameLegal.py | 621 | 3.640625 | 4 | #coding=utf-8
#ๅไธไธช็จๅบ๏ผๅคๆญ็จๆท่พๅ
ฅ็ๆ ่ฏ็ฌฆๆฏๅฆๅๆณ๏ผๆ นๆฎๆฐๅญ๏ผๅญๆฏไธๅ็บฟ็ญๅปๅคๆญ๏ผ
#ๅฉ็จๆญฃๅ่กจ่พพๅผ๏ผ
import re
myList = []
#ๅพช็ฏ็็ๅฐ่พๅ
ฅ็ๅญ็ฌฆไธฒๆทปๅ ๅฐๅ่กจไธญ
while True:
inputName = raw_put("่ฏท่พๅ
ฅๆ ่ฏ็ฌฆ")
if inputName == '':
break
else
myList.append(inputName)
#้ๅ่ฟไธชๅ่กจ๏ผๅๆญฃๅๆณๅน้
for x in myList:
if re.match('[A-Za-z]',s):#ๅคๆญๆฏๅฆๆฏ็ฑๅคงๅฐๅๅญๆฏ็ปๆใใ้่ฟ่ฟๅ
ฅไธ้ขไธไธช
if re.search('[_]|\w',s):#ๅคๆญๆฏๅฆๅซๆไธๅ็บฟใ
print 'True'
else:
print "False"
else:
print 'False'
|
5f61584f31fcab67e8d13d321d2ffc462ed2b3c8 | anuraghakeem/da | /7.py | 830 | 3.75 | 4 | import random
import time
def partion(a,first,last):
pivot=a[first]
left=first+1
right=last
while True:
while (left<=right and a[left]<=pivot):
left=left+1
while (right>=left and a[right]>=pivot):
right=right-1
if right<left:
break
else:
temp=a[left]
a[left]=a[right]
a[right]=temp
temp=a[first]
a[first]=a[right]
a[right]=temp
return right
def quicksort(a,first,last):
if first<last:
midpoint=partion(a,first,last)
quicksort(a,first,midpoint-1)
quicksort(a,midpoint+1,last)
a=[random.randint(0,100) for i in range(int(input("Enter a range: ")))]
print(a)
start=time.clock()
quicksort(a,0,len(a)-1)
print(a)
print(time.clock()-start)
|
da4e953bd96311b6bd5ad2d1ff30f1baf6ad0012 | JulyKikuAkita/PythonPrac | /cs15211/LongestSubstringWithAtLeastKRepeatingCharacters.py | 8,272 | 3.8125 | 4 | __source__ = 'https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/longest-substring-with-at-least-k-repeating-characters.py
# Time: O(26 * n) = O(n)
# Space: O(26) = O(1)
#
# Description: Leetcode # 395. Longest Substring with At Least K Repeating Characters
#
# Find the length of the longest substring T of a given string
# (consists of lowercase letters only) such that every character in T
# appears no less than k times.
#
# Example 1:
#
# Input:
# s = "aaabb", k = 3
#
# Output:
# 3
#
# The longest substring is "aaa", as 'a' is repeated 3 times.
# Example 2:
#
# Input:
# s = "ababbc", k = 2
#
# Output:
# 5
#
# The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
#
# Companies
# Baidu
#
# Recursive solution.
import unittest
# 20ms 100%
class Solution(object):
def longestSubstring(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
def longestSubstringHelper(s, k, start, end):
count = [0] * 26
for i in xrange(start, end):
count[ord(s[i]) - ord('a')] += 1
max_len = 0
i = start
while i < end:
while i < end and count[ord(s[i]) - ord('a')] < k:
i += 1
j = i
while j < end and count[ord(s[j]) - ord('a')] >= k:
j += 1
if i == start and j == end:
return end - start
max_len = max(max_len, longestSubstringHelper(s, k, i, j))
i = j
return max_len
return longestSubstringHelper(s, k, 0, len(s))
# If every character appears at least k times, the whole string is ok.
# Otherwise split by a least frequent character
# (because it will always be too infrequent and thus can't be part of any ok substring)
# and make the most out of the splits.
#
# 24ms 91.33%
class Solution2(object):
def longestSubstring(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
for c in set(s):
if s.count(c) < k:
return max(self.longestSubstring(t, k) for t in s.split(c))
return len(s)
class TestMethods(unittest.TestCase):
def test_Local(self):
self.assertEqual(1, 1)
if __name__ == '__main__':
unittest.main()
Java = '''
# Thought:
#
Java divide and conquer(recursion) solution
# 2ms 93.27%
class Solution {
private int findLongestSub(String s, int k, int start, int end) {
//count frequency of char over [start, end]
if (end < start) return 0;
int[] countArray = new int[26];
for (int i = start; i <= end; i++) {
countArray[s.charAt(i) - 'a'] ++;
}
//define a valid array isValid, isValid[i] = true if character c(i=c-'a')
//has at least k occurences
boolean[] isValid = new boolean[26];
//boolean fullValid to flag whether all characters over [start, end]
//have frequency >= k
boolean fullValid = true;
for (int i = 0; i < 26; i++) {
if (countArray[i] > 0 && countArray[i] < k) {
//find a character with freq < k
isValid[i] = false;
fullValid = false;
} else { //the freq >= k
isValid[i] = true;
}
}
if (fullValid) return end - start + 1;
// start to check from start to end
// if at index i, we find a character that has freq less than k
// we treat it as a separator and check the left substring
// from start up to this character(exclusive)
// and the right substring at i+1(i is the chr)
//define last start that will be the starting point
int lastStart = start;
int len = 0;
for (int i = start; i <= end; i++) {
char c = s.charAt(i);
int index = c - 'a';
if (isValid[index] == false) {
/*System.out.println("char is " + c);
System.out.println("last start is " + lastStart);
System.out.println("end is " + (i-1));*/
len = Math.max(len, findLongestSub(s, k, lastStart, i - 1));
//update lastStart to be i+1 (start checking the right substring
lastStart = i + 1;
}
}
//at the end if there is no invalid character
//we get the length of the qualified string
//note this step is important otherwise we will miss a qualified substring
len = Math.max(len, findLongestSub(s, k, lastStart, end));
return len;
}
private int longestSubstring(String s, int k) {
//store the frequency of each character in s
//if a character has frequency that is less than k
//we cannot include that character in our candidate substring
//it must be excluded, treat that character as the separator and search within
//the left substring[start, i) and right substring [i+1, end]
//where i is the index of that separator
//and compare the result length
//a candidate string cannot contain characters with overall frequency < k
return findLongestSub(s, k, 0, s.length()-1);
}
}
# 59ms 23.01%
class Solution {
public int longestSubstring(String s, int k) {
char[] str = s.toCharArray();
return dfs(str, 0, s.length(), k);
}
public int dfs(char[] str, int start, int end, int k) {
if (end - start < k) return 0;
int[] count = new int[26];
for (int i = start; i < end; i++) {
int idx = str[i] - 'a';
count[idx]++;
}
for (int i = 0; i < 26; i++) {
if (count[i] < k && count[i] > 0) {
for (int j = start; j < end; j++) {
if (str[j] == i + 'a') {
int left = dfs(str, start, j, k);
int right = dfs(str, j + 1, end, k);
return Math.max(left, right);
}
}
}
}
return end - start;
}
}
#62ms 21.43%
class Solution {
public int longestSubstring(String s, int k) {
return dfs(s, 0, s.length() - 1, k);
}
public int dfs(String s, int start, int end, int k) {
if (start > end) return 0;
int[] count = new int[26];
for (int i = start; i <= end; i++) {
count[s.charAt(i) - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (count[i] < k && count[i] > 0) {
int pos = s.indexOf((char)i + 'a', start);
int pos2 = pos + 1;
while (pos2 < s.length() && s.charAt(pos2) == (char)i + 'a') pos2++;
return Math.max(dfs(s, start, pos - 1, k), dfs(s, pos2, end, k));
}
}
return end - start + 1;
}
}
# https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/170010/Java-O(n)-Solution-with-Detailed-Explanation-Sliding-Window
# 1ms 100%
class Solution {
char[] cs;
int k;
public int longestSubstring(String s, int k) {
cs = s.toCharArray();
this.k = k;
return lss(0, s.length() - 1);
}
private int lss(int start, int end) {
if (end - start + 1 < k) return 0;
int[] count = new int[26];
for (int i = start; i <= end; i++) {
int index = (int)cs[i] - (int)'a';
count[index]++;
}
int s = start;
boolean begin = true;
int max = 0;
for (int i = start; i <= end; i++) {
int index = (int)cs[i] - (int)'a';
if (count[index] < k) {
if (begin) {
begin = false;
max = Math.max(max, lss(s, i - 1));
}
} else if (!begin) {
begin = true;
s = i;
}
}
if (begin && s == start) return end - start + 1;
if (begin) max = Math.max(max, lss(s, end));
return max;
}
}
'''
|
35892074dbfa13e334042edef7eeb736df23b25e | mnihatyavas/Python-uygulamalar | /Brian Heinold (243) ile Python/p32405.py | 1,481 | 3.796875 | 4 | # coding:iso-8859-9 Trke
from collections import *
dizge = "Bu fonksiyon verili dizge ierik karakterlerinin tekrar saysn karakter-tekrar ifti olarak ilk-rastlanan srada ierir."
sayar = Counter (dizge)
print ("sayar=Counter(dizge):", sayar)
print ("\nlist(sayar.items()):", list (sayar.items()) )
print ("\nlist(sayar.keys()):", list (sayar.keys()) )
print ("\nlist(sayar.values()):", list (sayar.values()) )
print ("\nsayar['a']:", sayar['a'] )
print ("sayar[' ']:", sayar[' '] )
print ("sayar['-']:", sayar['-'] )
print ("sayar['.']:", sayar['.'] )
#----------------------------------------------------------------------------------------------
L = list (sayar.items() )
print ("\nDizge = [", dizge, "]", sep="")
print ("\nCounter anahtar:deer ifti dkm:")
for i in range (len (L) ): print (L[i][0], ":", L[i][1], sep="", end=" ")
#----------------------------------------------------------------------------------------------
print ("\n\nAzalan rastlanma sklyla dkm:", sayar.most_common() )
print ("\nArtan rastlanma sklyla dkm:", sayar.most_common()[::-1] )
print ("\nEn sk rastlanan 3 karakter azalan srada:", sayar.most_common (3) )
print ("\nEn sk rastlanan 3 karakter artan srada:", sayar.most_common (3)[::-1] )
print ("\nEn az rastlanan 3 karakter azalan srada:", sayar.most_common()[-3:] )
print ("\nEn az rastlanan 3 karakter artan srada:", sayar.most_common()[:-4:-1] )
|
e84b116626c4bc88c4b54b95dfd8dd32f262b9b3 | Aasthaengg/IBMdataset | /Python_codes/p02819/s147614898.py | 332 | 3.703125 | 4 | X = int(input())
n = 10**6
is_prime = [True] * (n + 1)
is_prime[0] = False
is_prime[1] = False
for i in range(2, int(n**0.5) + 1):
if not is_prime[i]:
continue
for j in range(i * 2, n + 1, i):
is_prime[j] = False
for i, p in enumerate(is_prime):
if i >= X and p is True:
print(i)
break |
0a08c03796ba7e25c3d86c1e39d1263991435de6 | seany-web/Number-Guessing-Game | /guessing_game.py | 2,618 | 4.3125 | 4 | import random
def start_game():
# print welcome message when a player starts the application
print('?????????????????????????????????????????????????????\n\n')
print(' WELCOME TO THE NUMBER GUESSING GAME\n\n')
print('?????????????????????????????????????????????????????\n\n')
#set variables to hold the highscore, number of attempts the randomly generated solution number and start the game loop
high_score = None
attempts = 0
solution = random.randrange(1,10)
game_started = True #used to confirm is game state is active is set to false at the end of the game and only enabled if player plays again
#print(solution) #used for testing
#game loop starts here
while(game_started):
try:
#prompt the player to guess a number between 1 and 10
guess = input("I'm thinking of a number between 1 and 10... ")
#game logic starts here
if int(guess) > 10 or int(guess) < 1:
attempts += 1
print(f'{guess} is not in the range of 1 - 10. Please enter a number between 1 and 10.\n')
elif int(guess) > solution:
attempts += 1
print(f'The number I am thinking of is lower than {guess}\n')
elif int(guess) < solution:
attempts += 1
print(f'The number I am thinking of is higher than {guess}\n')
elif int(guess) == solution:
attempts += 1
game_started = False
if high_score == None or high_score > attempts:
high_score = attempts
print(f"\nThat's it! You answered correctly in {attempts} attempts.\n")
#repeatedly prompt player to play again until either 'yes' or 'no' are selected
while(True):
play_again = input('Would you like to play again? yes/no... ')
if play_again.upper() == 'YES':
#reset game variables
game_started = True
attempts = 0
solution = random.randrange(1,10)
#print(solution) # used for testing
print(f'\nThe current highscore is {high_score}. Can you beat it?\n')
break
elif play_again.upper() == 'NO':
print('Thanks for playing! See you next time.\n')
print('Exiting game.\n')
break
else:
print(f"'{play_again}' is not a recognised value. Please enter 'yes' or 'no'.\n")
except:
print(f"'{guess}' is not a recongnised value. Please enter a number between 1 and 10.\n")
#game logic ends here
#end of game loop
start_game() |
91e404df098e37cc0b3d13b8ba9c862ee3db08d5 | ashraf-a-khan/Leetcode-Python | /BalancedString.py | 393 | 3.71875 | 4 | """
1221. Split a String in Balanced Strings
"""
class Solution:
def balancedStringSplit(self, s: str) -> int:
count = 0
stack = 0
for i in s:
if i == 'L':
stack -= 1
elif i == 'R':
stack += 1
if stack == 0:
count += 1
return count |
470637a7ccf2812a2d3c9472167eea3ffc7634b7 | lightmanca/InterviewPrep | /DataStructures/LinkedStack.py | 1,436 | 4 | 4 | from DataStructures.LinkedListNode import LinkedListNode
class LinkedStack:
head = None
num_items = 0
def __init__(self, initial_stack=None):
# if you specify an initial stack items will be pushed from left to right.
if initial_stack:
for item in initial_stack:
self.push(item)
pass
def push(self, data):
node = LinkedListNode(data)
if self.head:
node.next = self.head
self.head = node
self.num_items += 1
def pop(self):
if self.num_items == 0:
return None
value = self.head.value
self.head = self.head.next
self.num_items -= 1
return value
def is_empty(self):
return self.num_items == 0
def remove_item(self, item_to_remove):
my_stack = LinkedStack()
found = False
while not self.is_empty():
item = self.pop()
if item == item_to_remove:
found = True
break
my_stack.push(item)
while not my_stack.is_empty():
self.push(my_stack.pop())
return found
def make_array_from_list(self):
array = []
node = self.head
while node:
array.append(node.value)
node = node.next
return array
def print_list(self):
print("Stack: {}".format(self.make_array_from_list()))
|
86daf6868b04b5ef1ad8371e72ce2e2aa36c8267 | PeterBeattie19/Daily-Coding-Problem | /Problem_118.py | 128 | 3.59375 | 4 | arr = list(map(int, input().split()))
def sort_square(x):
return sorted(map(lambda y: y**2, x))
print(sort_square(arr))
|
3bcd4069c342c636df752509799d1d90df3d6542 | goodDev-junhyuk/Pandas_Excercise | /P_Exam05.py | 372 | 3.671875 | 4 | import pandas as pd
# ๋ฆฌ์คํธ๋ฅผ ์ด์ฉํ์ฌ ํ ํ์ฉ ์ถ๊ฐํด์ ๋ฐ์ดํฐํ๋ ์์ ์์ฑ.
columns = ['KOSPI', 'KOSDAQ']
index = [2014, 2015, 2016, 2017, 2018]
rows = []
rows.append([1915, 542])
rows.append([1961, 682])
rows.append([2026, 631])
rows.append([2467, 798])
rows.append([2041, 675])
df = pd.DataFrame(rows, columns=columns, index=index)
print(df) |
2cf311dd94660f96acd73a214bc19d1b884c8679 | sanekvery/Python_Algos | /ะฃัะพะบ 2. ะัะฐะบัะธัะตัะบะพะต ะทะฐะดะฐะฝะธะต/task_9/task_9_1.py | 1,242 | 4.03125 | 4 | """
9. ะกัะตะดะธ ะฝะฐัััะฐะปัะฝัั
ัะธัะตะป, ะบะพัะพััะต ะฑัะปะธ ะฒะฒะตะดะตะฝั, ะฝะฐะนัะธ
ะฝะฐะธะฑะพะปััะตะต ะฟะพ ััะผะผะต ัะธัั. ะัะฒะตััะธ ะฝะฐ ัะบัะฐะฝ ััะพ ัะธัะปะพ ะธ ััะผะผั ะตะณะพ ัะธัั.
ะัะธะผะตั:
ะะฒะตะดะธัะต ะบะพะปะธัะตััะฒะพ ัะธัะตะป: 2
ะะฒะตะดะธัะต ะพัะตัะตะดะฝะพะต ัะธัะปะพ: 23
ะะฒะตะดะธัะต ะพัะตัะตะดะฝะพะต ัะธัะปะพ: 2
ะะฐะธะฑะพะปััะตะต ัะธัะปะพ ะฟะพ ััะผะผะต ัะธัั: 23, ััะผะผะฐ ะตะณะพ ัะธัั: 5
ะะะะกะฌ ะะะะะะ ะะซะขะฌ ะ ะะะะะะะฆะะฏ ะงะะ ะะ ะฆะะะ
"""
NUMBERUSER = int(input("ะกะบะพะปัะบะพ ะฑัะดะตั ัะธัะตะป?"))
SISTEMCOUNT = 0
NUMBERCOUNT = 0
DIVIDERNUM = 0
ASER = 0
LOTNUMBER = 0
WHATNUMBER = 0
while SISTEMCOUNT < NUMBERUSER:
NUMBERUSERINPUT = str(input("ะะฒะตะดะธัะต ะพัะตัะตะดะฝะพะต ัะธัะปะพ: ?"))
SISTEMCOUNT += 1
for i in str(NUMBERUSERINPUT):
NUMBERCOUNT += int(NUMBERUSERINPUT[ASER])
ASER += 1
if NUMBERCOUNT >= DIVIDERNUM:
DIVIDERNUM = NUMBERCOUNT
LOTNUMBER = NUMBERUSERINPUT
WHATNUMBER += 1
ASER = 0
NUMBERCOUNT = 0
print(f'Cัะผะผะฐ ัะธััะฐ ัะฐะฒะฝะฐ {DIVIDERNUM} ั ัะธัะปะฐ {LOTNUMBER} ะธ ะพะฝะพ ะฑะพะปััะตะต ะธะท ะฒะฒะตะดะตะฝัั
') |
26f7291e450f8910d98dd88a9078aa755d658177 | AbdullahElian1/data-structures-and-algorithms | /python/code_challenges/insert_sort/insert_sort/insert.py | 238 | 4.09375 | 4 | def insertionSort(arr):
for i in range(1,len(arr)):
j=i-1
temp=arr[i]
while j >=0 and temp < arr[j]:
arr[j+1]=arr[j]
j=j-1
arr[j + 1] =temp
return arr
arr=[1,6,9,33,55,77]
print(insertionSort(arr))
|
eabb98437ce3c17d8c8b0968f2a582b9f201bb2e | rangijayant15/Numerical_Analysis | /gauss_jacobi.py | 852 | 3.75 | 4 | import numpy as np
size=int(input("enter the size of matrix -->"))
A=np.zeros((size,size))
b=np.zeros((size,1))
X=np.zeros((size,1))
print("Enter the A matrix for Ax=b\n")
for i in range (0,size):
for j in range (0,size):
print ('entry in row: ',i+1,' column: ',j+1)
A[i][j] = int(input())
print("Enter the b vector\n")
for i in range(0,size):
print('enter in row: ',i+1)
b[i]=int(input())
print("Enter the initial x vector\n")
for i in range(0,size):
print('enter in row: ',i+1)
X[i]=int(input())
def gauss_jacobi(a,x,b,sze):
x_initial=x
D=np.zeros((sze,sze))
R=np.zeros((sze,sze))
for i in range(sze):
D[i][i]=a[i][i]
R=a-D
while(np.linalg.norm((np.matmul(a,x_initial)-b),2)>0.0001):
x_initial=np.matmul(np.linalg.inv(D),b-np.matmul(R,x_initial))
return x_initial
print("Answer is : ")
print(gauss_jacobi(A,X,b,size))
|
2d2974ceb597cd81fdbbbb6c8352e72a732dcb49 | beigerice/LeetCode | /284.py | 771 | 4.125 | 4 | class PeekingIterator(object):
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.i = iterator
self.n = None
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
if not self.n:
self.n = self.i.next()
return self.n
def next(self):
"""
:rtype: int
"""
if not self.n:
self.n = self.i.next()
tmp = self.n
self.n = None
return tmp
def hasNext(self):
"""
:rtype: bool
"""
if self.n:
return True
return self.i.hasNext()
|
86403347075e832f4d63b7d57f61431d9e8dbae4 | ii6uu99/ipynb | /python-note/python-programs-set-1-master/exercise_16.py | 950 | 4.53125 | 5 | print(
'-----------------------------------------\n'\
'Practical python education || Exercise-16:\n'\
'-----------------------------------------\n'
)
print(
'Task:\n'\
'-----------------------------------------\n'\
'Write a Python program to get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference."\n'
)
print(
'Solution:\n'\
'-----------------------------------------'\
)
#Task: b = a - 17;
#Conditions:
# a > 17 => b = 2(a - 17);
# a <= 17 => b = a - 17;
print("Calculation the difference between a given number and 17:")
a = int(input("Please enter the number = "))
if (a > 17):
b = 2 * (a - 17)
print("%d > 17, then = %d" % (a, b))
else:
b = a - 17
print("%d <= 17, then = %d" % (a, b))
print(
'\n-----------------------------------------\n'\
'Copyright 2018 Vladimir Pavlov. All Rights Reserved.\n'\
'-----------------------------------------'
) |
2889e220daa638c5055b5388ad553366dd79eb6b | SATHANASELLAMUTHU/MYPROJECT | /B43.py | 91 | 3.6875 | 4 | s1=raw_input("Enter the s1 string:")
s2=raw_input("Enter the s2 string:")
s=s1+s2
print(s)
|
a66b50e1d38eb7981b9baf416fa301ab04c69d88 | ivanmilevtues/python101 | /lesson_4/tasks.py | 854 | 3.90625 | 4 | def simplify_fraction(fraction):
frac_list = list(fraction)
a = min(frac_list)
for i in range(a + 1, 1, -1):
if frac_list[0] % i == 0 and frac_list[1] % i == 0:
frac_list[0] //= i
frac_list[1] //= i
return tuple(frac_list)
print(simplify_fraction((3, 9)))
print(simplify_fraction((1, 7)))
print(simplify_fraction((4, 10)))
print(simplify_fraction((63, 462)))
def sort_fractions(fraction):
for i in range(len(fraction)):
for k in range(i, len(fraction)):
if(fraction[i][0] / fraction[i][1] > fraction[k][0] / fraction[k][1]):
fraction[i], fraction[k] = fraction[k], fraction[i]
return fraction
print(sort_fractions([(5, 6), (22, 78), (22, 7), (7, 8), (9, 6), (15, 32)]))
print(sort_fractions([(2, 3), (1, 2), (1, 3)]))
print(sort_fractions([(2, 3), (1, 2)]))
|
eb3cbcb200931746be2ce09382c166ffd2dcb52b | GeertenRijsdijk/Theorie | /code/algorithms/simann.py | 3,103 | 4.21875 | 4 | '''
simann.py
Authors:
- Wisse Bemelman
- Michael de Jong
- Geerten Rijsdijk
This file implements the simulated annealing algorithm.
Parameters:
- grid: the grid object
- T: initial temperature
- cooling_rate: amount the temperature decreases each iteration
- stopT: the temperature at which the algorithm stops, if T is below it
- swap_prob: the probability of swapping houses at an iteration
Returns:
- price_list: a list containing prices per iteration, which can be plotted.
'''
from .random import *
# Function that swaps two houses
def swap(grid, index, score, T, price_list, type, x, y):
# Find random swap
ind = np.random.randint(0, len(grid.houses))
house_1 = grid.houses[ind]
rest_houses = [h for h in grid.houses if h[0] != house_1[0]]
ind2 = np.random.randint(0, len(rest_houses))
house_2 = rest_houses[ind2]
new_score = grid.price_after_swap(house_1, house_2)
# Continue only if the move is legal
if new_score > 0:
# Calculate probability of swapping
p = probability_function(score, new_score, T)
if p > np.random.uniform(0,1):
# Swap the houses
#score = new_score
price_list.append(score)
grid.swap(house_1, house_2)
return new_score
return score
# Function that moves a house
def move(grid, index, score, T, price_list, type, x, y):
moves = [(-1, 0), (1, 0), (0, -1), (0, 1)]
# Choose a random move
movex, movey = moves[np.random.randint(0,len(moves))]
new_score = grid.calculate_price_of_move(index, movex, movey)
# Continue only if the move is legal
if new_score != 0:
# Calculate probability of moving
p = probability_function(score, new_score, T)
if p > np.random.uniform(0,1):
# Move the house
# score = new_score
price_list.append(score)
grid.remove_house(index)
grid.place_house(type, x + movex, y + movey, index)
return new_score
return score
# Function that calculates the probability of moving to a new state
def probability_function(old_score, new_score, T):
if new_score > old_score:
return 1
else:
return np.exp((new_score - old_score) / T)
# Simulated annealing algorithm with a chance to swap houses
# instead of moving them
def simann(grid, T=10000000, cooling_rate=0.003, stopT=0.1, swap_prob=0.1):
# initialize a random start state
random(grid)
score = grid.calculate_price()
price_list = [score]
# Based on T do random moves that may be accepted
while T > stopT:
# Choose a random house
index = np.random.randint(0,len(grid.houses))
house = grid.houses[index]
type, x, y = house
# Choose whether to move or swap based on swap_prob
if swap_prob > np.random.uniform(0,1):
score = swap(grid, index, score, T, price_list, type, x, y)
else:
score = move(grid, index, score, T, price_list, type, x, y)
# Cooling rate update
T *= 1 - cooling_rate
return price_list
|
d689ca495f846c971d86a00ef8448d92493ed2bf | funnydog/AoC2018 | /day17/day17.py | 3,370 | 3.546875 | 4 | #!/usr/bin/env python
import sys
import re
UP = (0, -1)
RIGHT = (1, 0)
DOWN = (0, 1)
LEFT = (-1, 0)
def add(a, b):
return (a[0]+b[0], a[1]+b[1])
class Map(object):
def __init__(self, txt):
vertical = re.compile(r"x=(\d+), y=(\d+)..(\d+)")
horizontal = re.compile(r"y=(\d+), x=(\d+)..(\d+)")
self.data = {}
for line in txt.splitlines():
m = vertical.match(line)
if m:
x, y1, y2 = map(int, m.groups())
for y in range(y1, y2+1):
self.data[x, y] = "#"
m = horizontal.match(line)
if m:
y, x1, x2 = map(int, m.groups())
for x in range(x1, x2+1):
self.data[x, y] = "#"
self.ymin = 1e12
self.ymax = 0
for _, y in self.data.keys():
if self.ymin > y: self.ymin = y
if self.ymax < y: self.ymax = y
def open(self, pos):
return pos not in self.data or self.data[pos] == "|"
def fill(self, x, y):
stack = []
stack.append((x, y+1))
while stack:
pos = stack.pop()
below = add(pos, DOWN)
if pos[1] > self.ymax:
pass
elif self.data.get(pos, ".") in "~#":
pass
elif self.data.get(below, ".") in "~#":
left = pos
while self.open(left) and not self.open(add(left, DOWN)):
self.data[left] = "|"
left = add(left, LEFT)
right = pos
while self.open(right) and not self.open(add(right, DOWN)):
self.data[right] = "|"
right = add(right, RIGHT)
if self.data.get(left, ".") == "#" and self.data.get(right, ".") == "#":
left = add(left, RIGHT)
while left != right:
self.data[left] = "~"
left = add(left, RIGHT)
# add the sand above
stack.append(add(pos, UP))
else:
stack.append(left)
stack.append(right)
elif pos not in self.data:
self.data[pos] = "|"
stack.append(below)
def count(self):
sand = water = 0
for p, t in self.data.items():
if p[1] < self.ymin:
pass
elif t == "|":
sand += 1
elif t == "~":
water += 1
return sand, water
def print(self):
sand = 0
xmin, xmax = 1e12, -1e12
for x, _ in self.data.keys():
if xmin > x: xmin = x
if xmax < x: xmax = x
for y in range(self.ymax+1):
print("".join(self.data.get((x, y), NONE) for x in range(xmin, xmax+1)))
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: {} <filename>".format(sys.argv[0]), file=sys.stderr)
sys.exit(1)
try:
with open(sys.argv[1], "rt") as f:
txt = f.read().strip()
except:
print("Cannot open {}".format(sys.argv[1]), file=sys.stderr)
sys.exit(1)
m = Map(txt)
m.fill(500,0)
#m.print()
sand, water = m.count()
print("Part1:", sand+water)
print("Part2:", water)
|
3cef18816c58994adefeddc9ed63ad72f5aa4330 | VarshaRadder/APS-2020 | /Code library/137.K-diff Pairs in an Array.py | 732 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 18:07:24 2020
@author: Varsha
"""
'''
A k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k
'''
def find_pairs(L,k):
L.sort()
N = len(L)
i = pairs = 0
j = 1
while j < N:
if j < N - 1 and L[j] == L[j + 1]:
j += 1
elif L[j] == L[i] + k:
pairs += 1
i += 1
j += 1
elif L[j] > L[i] + k:
i += 1
elif L[j] < L[i] + k:
j += 1
j = max(j, i + 1)
return pairs
L=list(map(int,input().split()))
k=int(input())
print(find_pairs(L,k)) |
1a3bf952bc6fad62e1466fa02f5e98e108a1eb86 | ueg1990/aids | /aids/stack/queue_two_stacks.py | 784 | 4.28125 | 4 | '''
Implement Queue data structure using two stacks
'''
from stack import Stack
class QueueUsingTwoStacks(object):
def __init__(self):
'''
Initialize Queue
'''
self.stack1 = Stack()
self.stack2 = Stack()
def is_empty(self):
'''
Return True if queue if empty else False
'''
return self.stack1.is_empty() and self.stack2.is_empty()
def enqueue(self,value):
'''
Enqueue item to queue
'''
self.stack1.push(value)
def dequeue(self):
'''
Dequeue item from queue
'''
if not self.stack2.is_empty():
return self.stack2.pop()
while not self.stack1.is_empty():
self.stack2.push(self.stack1.pop())
return self.stack2.pop()
def __len__(self):
'''
Return number of items in Queue
'''
return len(self.stack1) + len(self.stack2)
|
4c4b35a4f1cab4eb148a59a6eb77064da189df26 | IsaacLeh1/Novel | /text.py | 77,789 | 4.03125 | 4 | #Pages
def stop():
input("press exit to end program")
quit()
def pg1a():
print("""Do not read this book straight through from beginning to end! These pages contain many different
adventures you can go on as you journey under
the sea. From time to time as you read along, you
will be asked to make a choice. Your choice may
lead to success or disaster!
The adventures you take are a result of your
choice. You are responsible because you choose!
After you make your choice follow the instructions
to see what happens to you next.
Rememberโyou cannot go back! Think carefully
before you make a move! One mistake can be
your last ... or it may lead you to fame and
fortune!""")
def pg2a():
print("""You are an underwater explorer. You are leaving to explore the deepest oceans. You must find
the lost city of Atlantis. This is your most challenging assignment.
It is morning and the sun pushes up on the
horizon. The sea is calm. You climb into the narrow pilot's compartment of the underwater vessel
Seeker with your special gear. The crew of the
research vessel Maray screws down the hatch
clamps. Now begins the plunge into the depths of
the ocean. The Seeker crew begins lowering by a
strong, but thin cable. Within minutes, you are so
deep in the ocean that little light filters down to
you. The silence is eerie as the Seeker slips deeper
and deeper. You peer out the thick glass porthole
and see fish drifting past, sometimes stopping to
look at youโan intruder from another world.""")
def pg3():
print("""Now the cable attaching you to Maray is extended almost to its limit. You have come to rest on
a ledge near the canyon in the ocean floor that
supposedly leads to the lost city of Atlantis.
You have a special sea suit that will protect you
from the intense pressure of the deep if you choose
to walk about on the sea bottom. You can cut
loose from the cable if you wish because the
Seeker is self-propelled. You are now in another
world.\n\nIf you decide to explore the ledge
where the Seeker has come to rest,
turn to page 6.
If you decide to cut loose from
the Maray and dive with the Seeker
into the canyon in the ocean floor,
turn to page 5.""")
def pg5():
print("""You radio a status report to the Moray and tell
them that you are going to cast off from the line
and descend under your own power. Your plan is
approved and you cast off your line. Now you are
on your own. The Seeker slips noiselessly into the
undersea canyon.
As you drop into the canyon, you turn on the
Seeker's powerful searchlight. Straight ahead is a
dark wall covered with a strange type of barnacle
growth. To the left (port) side you see what appears to be a grotto. The entrance is perfectly
round, as if it had been cut by human hands.
Lantern fish give off a pale, greenish light. To the
right (starboard) side of the Seeker you see bubbles rising steadily from the floor of the canyon.
If you decide to investigate
the bubbles, turn to page 8.
If you decide to investigate the grotto
with the round entrance, turn to page 9.
""")
def pg6():
print("""Your sea suit will protect you from the intense
pressures of the deep. It is a tight fit and takes you
some time to put it on. Finally you slip from the
airlock of the Seeker and stand on the ocean floor.
It is a strange and marvelous world where your
every move isslowed down. You begin to explore
with your special hand-held searchlight. You
examine the ledge by the canyon.
Suddenly, a school of bright yellow angel fish
dart by, almost brushing you. What made them
move so fast? Are they being chased?
Then you see it. The Seeker is in the grips of a
huge sea monster. It is similar to a squid, but it is
enormous. The Seeker is just a toy in its long,
powerful tentacles. You seek shelter behind a rock
formation. You know the spear gun you carry will
be useless against this monster. It looks asthough it
will destroy the Seeker. Fish of allsizes huddle with
you in an attempt to escape the monster.
If you stay hidden close to
the Seeker, turn to page 10.
If you try to escape in the
hope that rescuers willsee
you, turn to page 12.""")
def pg8():
print("""Carefully, you maneuver the Seeker between
the walls of the canyon.
On the floor of the canyon, you discover a large
round hole out of which flow the large bubbles.
The Seeker is equipped with scientific equipment
to analyze the bubbles. It also has sonar equipment that can measure the depth of any hole.
If you decide to analyze the bubbles,
turn to page 11.
If you decide to take sonar readings,
turn to page 15.""")
def pg9():
print("""You pilot the Seeker through the rounded entrance to the grotto. Once inside, your searchlight
picks up what appear to be docks and piers along
the grotto walls. The Seeker's searchlight is not
very powerful. However, you do have a special
laser light which would light up the grotto like
daylight. Unfortunately, the laser light can only be
used twice for very short periods before it must be
recharged aboard the Maray, now more than
2,000 feet above you on the surface.
If you decide to use the laser light,
turn to page 16.
If you decide to cruise further into
the grotto, turn to page 14.""")
def pg10():
print("""The giant squid tosses and turnsthe Seeker, but
finally the creature growstired of its new game and
jets off with an enormous squirt of water. You now
are free to leave your hiding place and examine
the Seeker for damage.
To your dismay, the airlock entrance has been
jammed shut. You are locked out of the Seeker.
The crew of the Maray, however, suspected trouble when you did not respond to a routine radio
check and they are now lowering an escape platform to you. Once on the platform, you radio them
to start the slow pull to the surface. To avoid the
bendsโrapid expansion of nitrogen bubbles in
your bloodโthey will have to bring you up very
slowly.
Just as the platform begins to move, the giant
squid suddenly returns as if from nowhere. It is
headed directly at you.
If you decide to use the laser light,
turn to page 16.
If you decide to cruise further into
the grotto, turn to page 14.""")
def pg11():
print("""You squeeze into your sea suit and, outside the
Seeker, you use special equipment to analyze the
bubbles. As you work, you clumsily knock against
the valve that dumpsthe compressed air necessary
to make the Seeker rise to the surface. There is
nothing to be done about it; so you continue to
analyze the bubbles. They contain a high percentage of oxygen and no poisonous gases. Perhaps
they are coming from some area below the sea
where human-type beings can live and breathe.
Perhaps they are coming from Atlantis.
You wonder whether you should try the
Seeker's drilling arm to enlarge the source of the
bubbles so you can explore it with the Seeker. But
you are also very worried about the Seeker's loss
of rising capability. You might also be able to trap
the bubbles and use them to raise the Seeker.
If you try to collect the bubbles
coming from the hole to fill the tanks
of the Seeker, turn to page 24.
If you decide to drill, turn to page 22.""")
def pg12():
print("""Moving cautiously, you climb up the sides of the
canyon hoping to reach the ocean floor. You leave
the Seekerin the grips of the giantsquid. Your plan
is to signal for help with a dye marker that will float
to the surface and make a bright yellow patch in
the water. The crewmen above have been instructed to watch for such emergency signals.
They will send help.
Once you reach the ledge above the canyon
and feel slightiy safer, you see the most feared of all
sea creaturesโ a huge shark. It begins to circle
towards you and you know that you are its target.
You wonder whether you should fire your
emergency propulsion charge that will send you
rapidly to the surface. The shark is fast; he might
catch you anyway. You also know that you will get
the bends from the rapid rise to the surface.
If you decide to fire the special
propulsion charge to get to the surface,
turn to page 21.
If you decide to wait quietly
hoping that the shark will go away,
turn to page 19.""")
def pg14():
print("""You cruise silently into the grotto. Its roof seems
to slope upward and you follow the slope. The
depth finder shows that you are rising quite
rapidly. Perhaps you will reach the surface and
open air. Then the roof of the grotto stops sloping
upward. Before you is a perfectly round metallic
hatch made of a metal that you have never seen
before. With the mechanical arm of the Seeker
you try to open the hatch. It will not open. You
begin to send radio signals at the door hoping to
make contact on the other side.
If you decide to blow the hatch open
with an explosive charge,
turn to page 26.
If you decide to continue
transmitting radio communicationsthrough
the hatch, turn to page 28.""")
def pg15():
print("""You maneuver the Seeker next to the hole and
begin to take sonar readings to determine the
depth of the hole. To your amazement, the sonar
readings indicate that the hole is extraordinarily
deepโ it might reach the center of the earth!
What lies down there? Where are the bubbles
coming from? Is Atlantis beneath you?
Then you notice a disturbing reading on your
instruments; a mild earthquake has occurred. The
Seeker is not damaged, but the earthquake could
set up a tsunami wave on the surface causing the
Moray to leave forsafer areas. It might be dangerous not to get back to the surface and leave with
the Moray. On the other hand, you are perhaps on
the verge of one of the world's greatest discoveries.
If you decide to descend into the hole,
turn to page 23.
If you decide to return to the surface,
turn to page 27.""")
def pg16():
print("""The beam from the laser light illuminates the
entire grotto. Far back on the floor of the grotto is a
submarine! Cautiously, you maneuver the Seeker
closer. You identify it asthe submarine that mysteriously disappeared in the Bermuda Triangle almost a year
before. The Bermuda Triangle is more
than 2000 miles away.
The submarine is apparently not damaged, but
it is covered with a slimy algae. Beautiful fish swim
around it as though it is their own special prize.
Then you notice that the main hatch is free of
algae!
If you decide to descend into the hole,
turn to page 23.
If you decide to return to the surface,
turn to page 27.""")
def pg17():
print("""With a rush of water, the giant squid attacks you.
Two 20 foot tentacles with their pulsing suction
cups reach out trying to ensnare you. You dive off
the platform and rapidly fire two of your spears.
They strike the squid close to its two monstrous
eyes. But the squid keeps on coming.
One of the tentacles wraps around your diving
helmet and ruptures the seal to your suit. You fire
your last spear hoping to hit the monster in a
vulnerable spot. Water is beginning to trickle into
your suit. You signal the Maray to haul you up
fastโ "Emergency Hoist." You must have hit the
squid. It floats away writhing and thrashing. You
think you're about to black out.
You wake up on the deck of the Moray and are
quickly rushed to the decompression chambers to
ward off the effect of the bends. In a few days you
are better and start to worry about diving into the
abyss again.
If you decide to descend into the hole,
turn to page 23.
If you decide to return to the surface,
turn to page 27.""")
def pg18():
print("""As they begin the rapid hauling, you lose your
ability to function in the deep. You start to get dizzy
and your arms and legs feel weak. You lose your
hold on the platform and drift in the water
exhausted. Then you see a dolphin heading toward you. You know that these marvelous
mammalssometimes help people in trouble. Will it
help you?
If you decide to descend into the hole,
turn to page 23.
If you decide to return to the surface,
turn to page 27.""")
def pg19(): #ending
print("""You wait for the shark to go away. But then you
notice other sharks coming to join in the hunt.
They circle you, coming closer and faster each
time. It is too late. There is no escape!
The End""")
input("Click enter to exit")
stop()
def pg21(): #ending
print("""You fire the special propulsion charge and zoom
upward through the water, frightening schools of
fish as you go. You become dizzy and lose track of
where you are. The world seems upside down.
The shark is nowhere around, you hope. Then
you break through to the surface floating about a
half mile from the Maray.
The lookouts spot you in the water and quickly
rescue you. Unfortunately, the rapid ascent has
given you a bad case of the bends. It takes a long
time to decompress. And when you are finally all
right, the ship's doctor informs you that your
underwater days are over. Someone else will have
to find Atlantis.
The End""")
input("click enter to exit")
def pg22():
print("""As you begin to drill, the stream of bubbles
increases.
The stream of bubbles is strong enough now to
ruffle the surface of the sea. You could try to
surface now and locate the exact position of the
bubble area. Then you could make plans with the
scientists aboard the Moray about what to do next.
But also, you could simply explore the hole with
the Seeker to determine the source of the bubbles
now! There is great risk in entering the hole, but it
could lead to the source of the bubbles and maybe
to Atlantis.
If you explore, turn to page 38.
If you try to surface, turn to page 35.""")
def pg23(): #ending
print("""Now is the time for decision. You check all the
controls of the Seeker, grit your teeth, and push
the control column into the deep dive position.
Down, down you go where no person has ever
ventured. The Seeker is built for deep, deep dives,
but you are descending rapidly mile after mile into
the deep. The pressure is intense, the darkness is
complete, and the depth guage indicates an incredible 15 miles. You quickly reverse the control
column. Warning lights flare up on your control
panel; they show that gravitational forces are now
stronger than the Seeker's propulsion motors. You
have passed the point of no return and your journey downward will continue in utter darkness until
the water pressure is too great for the Seeker. This
is the final voyage.
The End""")
input("click enter to exit")
stop()
def pg24():
print("""You are able to capture the bubbling gases and
fill the tanks of the Seeker, enough to allow it to
rise. Slowly, the Seeker rises out of the canyon,
scattering schools of brightly colored fish, and
brushing past underwater plants that wave like
palm trees in a wind. Just as you reach the ledge at
the top of the canyon, you see what appears to be
an old road! Rocks along its side seem to be guard
rails. Could this be a path that leads to the lost city
of Atlantis? You anchor the Seeker and prepare to
investigate more closely.""")
def pg26(): #ending
print("""The only way to get beyond the door isto blast it
away, or so you believe. The Seeker's laser cannon is powerful and you position the Seeker to fire.
Pushing the fire button, you send a powerful beam
at the hatch. Nothing happens. Then you advance
the cannon control to full emergency force. Again
you push the button and the beam dissolves the
hatch instantly. A flood ofsea water rushesinto the
giant hole, carrying you with it into an air-filled
cavern beyond. The water fills the cavern with
speed and explosive force. You see several people
scurrying towards escape hatches. IT IS TOO
LATE! You did the wrong thing.
The End""")
input("click enter to exit")
stop()
def pg27():
print("""Deciding to return to the surface, you direct the
Seeker cautiously back along the side of the canyon in the ocean floor. Without warning, the
Seekeris gripped in a powerful current thatsweeps
it toward a grotto. Once in the grotto, the current
carries you to what appears to be a large metal
door. It swings open and the Seeker is swept inside. The door closes, the water in the grotto drains
away, and you step out into a chamber that you
decide must be made by human hands.
A door opens in the wall, two people dressed in
simple clothes come towards you. One of them
says, "Welcome to Atlantis. We have been expecting you."
What a discovery! You have found the lost continent and its civilization. The two people tell you
that although citizens of Atlantis occasionally journey to the upper world, anyone who happens
upon Atlantis is never permitted to leave. The
Atlanteans are not cruel but fear discovery of their
world.
They want you to follow them and you agree.
But you have another thought. Perhaps you could
blast your way out of the chamber with the
Seeker's laser cannon.
If you decide to follow the people and
join the Atlantean society, turn to page 39.
If you decide to make a dash for
the Seeker and try to blast through the closed
door with the laser cannon, turn to page 40.
If you decide to follow the people and
join the Atlantean society, turn to page 39.
If you decide to make a dash for
the Seeker and try to blast through the closed
door with the laser cannon, turn to page 40.""")
def pg28():
print("""The radio transmissions seem to be failing, and
you grow tired of sending signals through the
closed door. You are just about to give up when
the doorsuddenly swings open revealing behind it
a cavern with another door. You enter the cavern
cautiously and receive a radio signal in English. It
tells you that you are welcome here, but that once
you enter this place, you may never return to the
world above. It is up to you to decide.
If you decide to go on
and investigate what might be Atlantis,
turn to page 41.
If you decide to retreat, turn to page 42.""")
def pg29():
print("""The submarine is indeed mysterious. You now
have on your sea suit and you open the hatch on
the conning tower and enter the sub. It is amazingly clean and in order. There are no signs of life,
but there are also no signs ofstruggle or trouble. In
the control room, you see a piece of mystifying
equipment that just doesn't belong on this sub.
A voice begins telling you that, thousands of
years ago, the leaders of Atlantis realized that their
continent was slipping into the sea. They discovered a large underground cavern and built new
forms of living quarters for their people. Later
when Atlantis was deep beneath the ocean, some
of their scientists discovered and perfected an operation enabling them to breathe under water.
The voice, which sounds friendly, also tells you
that there are two groups in Atlantis. One group is
good and the other is evil. The voice invites you to
enter the world of Atlantis and gives directions and
instructions to a secret passageway to the underwater city.
As you follow directions, you spy an unbelievable underwater craft with several people in it. It
must be an Atlantean ship, but are the people
good or evil? Do they know of the secret passageway?
If you hurry in, trying to reach
the secret passageway without being seen,
turn to page 43.
If you rush back to the Seeker
trying to escape danger, turn to page 44.""")
def pg31(): #ending
print("""You cruise through the grotto past the wreck of
the submarine and then you spot another ship
wreck. And then another. They, too, are covered
with algae, but they appear undamaged. Maybe
people from Atlantis capture ships in the Bermuda
Triangle and bring them here. Then you see
another ship, but this one is a three-masted
schooner of the type used in the early 1800s. Its
rigging isfestooned with algae, and fish swim lazily
around its mast.
Your curiosity captures you and you put on your
sea suit. Leaving the Seeker, you move towards
the old sailing ship. Suddenly a thirteen-foot long
deadly poisonous sea snake strikes from behind
the forward cabin and bites you in the soft flesh
between the fingers of your right hand. There is no
antidote to the deadly poison.
The End""")
input("click enter to exit")
stop()
def pg32(): #ending
print("""With great sorrow, you decide that it is wisest to
leave the expedition now. You can't risk returning
to the great depths below. So, you reluctantly
return to the United States.
You are invited to tell of your adventures on
several major television shows. While on one such
show, a special news flash announces to the world
the discovery of Atlantis. You regret your decision,
but you didn't really have a choice. Did you?
The End""")
input("click enter to exit")
stop()
def pg33():
print("""You can't resist the adventure beneath the sea.
You must go down again, and after several weeks
of rest, you enter the Seeker and slip quickly into
the deep. You bring the Seeker to rest by the great
canyon in the ocean bottom and, wearing your
special suit, you venture out into the depths. There
are no signs of the giant squid and you feel safe.
Rounding a rock formation, you come upon the
wreck of an ancient Greek ship. How strange to
find this ship, intact, so far below the surface. What
brought it here? Was it visiting Atlantis before the
lost continent slipped beneath the sea?
You take pictures and make notes in your special undersea book. Maybe this ancient ship hides
the secret to Atlantis.
If you go aboard
the Greek ship, turn to page 45.
If you return to the surface to
report your findings, turn to page 46.""")
def pg34():
print("""The dolphin looks at you, and you even imagine
that he is smiling at you. You grab one of his
flippers and with a powerfulswitch of his body, the
dolphin swims upward. In a short time, you break
through to the surface. You blink in the brightsun.
The Maray is nowhere in sight. You are lost far at
sea.
The dolphin dives beneath the surface with you
still clinging to him. He speeds off and within 20
minutes you are next to the Moray. The dolphin
must have heard the Moray's engine noises underneath the water.
Once aboard, everyone congratulates you on
your escape. You will go down again, but the
thought keeps haunting you: What if your luck has
run out?
If you decide to dive again
the next day, turn to page 48.
If you decide to give up
the expedition, turn to page 47.""")
def pg35():
print("""You suddenly realize the stream of bubbles is
powerful enough to raise the Seeker. You guide
the Seeker into the bubble stream and it heads
towards the surface. As you swirl upward, you
begin to notice increasing amounts of brown
kelpโ seaweed. Near the surface, you become
entangled in the seaweed. The instruments in the
Seeker indicate that the propellers and the steering
mechanisms will not work.
You put on your sea suit and go out to see what
can be done. Once outside in the kelp, you realize
that you can't free the Seeker. You start to swim
for the surface but then you are soon completely
stuck in the clinging seaweed. You are trapped and
unable to go forward or return to the Seeker.
If you decide to keep struggling
towards the surface, turn to page 50.
If you decide to rest quietly,
gain strength, and work out a plan,
turn to page 53.
If you decide to keep struggling
towards the surface, turn to page 50.
If you decide to rest quietly,
gain strength, and work out a plan,
turn to page 53.""")
def pg37(): #ending
print("""The dolphin might help and might not. You
decide to chance it alone. So, up you head, swimming towards the surface. The dolphin follows for
some time, and then swims off. You rest for awhile
about 300 feet below the surface before your final
ascent.
Then a large fishโ ugly, lumpy, puffed up, and
covered with black and white markings swims towards you. Its bulging eyes fasten on you. It is a
big-mouthed grouper, a fish which does not
bother to bite its victims, butsimply swallowsthem
whole.
It looks as though you are its next meal.
The End""")
input("click enter to exit")
stop()
def pg38():
print("""You decide to guide the Seeker into the new
passageway to the bubble source. Suddenly the
Seeker is swept downward as if pulled by a giant
magnet. You lose consciousness. When you
awake, you are in a well-lighted and comfortable
room. Three people are standing close to you.
They look normal and appear to be friendly.
The middle one speaks. "You are in the nether
region of Atlantis. Thisis a visitors'reception room.
If you wish to come into the city of Atlantis, then
follow us; but you may never return to your world.
If you wish to leave now, we will escort you safely
to the surface. It is your choice. We do not wish to
harm you."
If you follow them into
the city of Atlantis, turn to page 55.
If you decide to return
to the surface, turn to page 51.""")
def pg39():
print(""""You are led to a room. The floors are a rich
marble. The walls glow. The ceiling is like being
inside a diamond looking through the many facets.
A person who immediately commands respect
beckons you with firmness and kindness to come
to her.
"Welcome to Atlantis. Thousands of years ago
we learned that we were about to slip into the sea.
Our people prepared for the calamity by building a
new city inside an extinct volcano. We have lived
here in peace and harmony ever since. We have
no sunlight, nor stars to gaze at, but we have other
spaces to meditate upon."
She tells you about a group of people called the
Nodoors. If you wish, you can live with them, but
you cannot leave Atlantis.
A bearded man is to be your escort. Atlantis is a
beautiful city. Buildings merge one into another,
colors radiate light, and coral branches fill courtyards. There is a sense of well-being and peace.
It would be pleasant here, but you don't want to
be a prisoner. Maybe there would be a better
chance to escape if you join the Nodoors. You ask
your guide about them.
"Oh, we believe they are dangerous, but we
don't really know. They live in the center of the old
volcano. If you wish, I can take you there."
If you decide to join the Nodoors,
turn to page 56.
If you decide to remain with
the Atlanteans and perhaps get a
chance to escape, turn to page 57.""")
def pg40(): #ending
print("""The Atlanteans have lived in peace for thousands
of years. They have no love of warfare. Their
civilization is technologically very advanced and a
sensing mechanism tells them that you are about
to use your laser cannon. They quickly fire a special beam at the Seeker that makes all its functions
stop. You are now powerlessto escape. They walk
up calmly to the Seeker and tell you to come with
them to Atlantis.
"You are now part of Atlantis. We understand
your fear, but do not be frightened. No harm will
come to you and your life will be full. Follow us."
As you walk with them, into a new world, you
wonder if you will ever see the sky again.
The End""")
input("click enter to exit")
stop()
def pg41():
print("""You are greeted by a group of people who look
like ordinary human beings except that there are
gill-like slits on their necks. Their bare feet have
skin between the toes forming a web. They order
you to put on your sea suit, pull you quickly from
the Seeker, and lead you towards their city. On the
way they show you the zoo where there are animals from the world above the sea. There is a
glass-like cage surrounding them filled with air,
allowing them to live below the sea.
The leader of the group explainsthat if you wish
you may eithersubmit to an operation to have gills
inserted so that you may breathe underwater, or
you may join the other animals in the zoo.
If you agree to the operation,
turn to page 58.
If you go to the zoo, turn to page 59.""")
def pg42():
print("""Back aboard the Seeker, you radio the Maray that you are surfacing to make a plan.
While rising out of the giant crevice-like canyon, you spot what appears to be a road running along the top of the ledge.
What is this? The scientists aboard the Maray had mentioned the possibilities of finding signs of the ancient civilization,
such as roads. You must investigate.
Turn to page 6.""")
def pg43():
print("""You escape being seen by the submarine craft.
Following the instructions you enter a passageway. At the end of the passageway is an airlock
door and beyond it an incredibly large air-filled
cavern. Perhaps it is the inside of an extinct volcano.
The land is pleasant, although strange to your
experience. A softsubstance covers the ground. It
seems to be alive. You can't tell. A gentle light
comes from the sides of this huge cavern. It reminds you of early morning light just before the
sun rises.
A group of people approach you with friendly
gestures. They are wearing simple clothes much
like the clothes people wore in ancient Greece.
They are kind and generous. You remove your
diving suit to find that the air is good to breathe.
These people speak a language that is unknown
to you, but one of them acts as an interpreter. You
find out that this is Atlantis. They tell you it is
governed by a man who is greedy, selfish, and
dangerous. The people are like slaves. Everyone is
unhappy except a few who serve the ruler as his
lieutenants. These new friends ask for your help.
Perhaps you can help them escape.
If you decide to leave
your new friends and search for
the ruler, turn to page 60.
If you decide to help your
new friends escape, turn to page 61.""")
def pg44():
print("""Quickly you get into the Seeker in an attempt to
escape the strange submarine. You notice that the
sub is chasing you so you put on full emergency
ascent power. You could use your laser cannon to
blast the sub, but you do not wish to hurt anyone.
The ascent towardsthe surface isswift, but a few
fathoms from the surface all systems on the Seeker
fail. You are suspended in the water in a helpless
position. It seems that a mysterious force has disabled you.
If you decide to wait on board
the Seeker for help from the Maray,
turn to page 64.
If you try to escape from
the Seeker and try for the surface on
your own, tum to page 63.""")
def pg45():
print("""Cautiously you enter the ship's cabin. Clay jugs
called amphorae, once filled with oils and wines, are
strewn about. There are no remains of the crew.
You do have a sense of being in ancient Greece
and it is a strange feeling.
A door leads to a smaller cabin. On a table near
the rear of this cabin is a golden box. You open it
and find the remains of a map. It does not show
Atlantis. It shows that the ship was searching for a
hole that leads to the center of the earth!
You return to the Seeker and use the map to
locate this incredible shaft to the center of the
earth. Using some guesswork to interpret the map,
you discover the tunnel opening, which appears to
be roughly 100 feet in diameter. The sonar
readings indicate the hole has no bottom.
If you decide to descend into the hole,
turn to page 65.
If you decide it is time to go
back up to the surface, turn to page 66.""")
def pg46():
print("""The trip back to the surface is smooth, and
finally the Seekeris hauled aboard the Maray. You
climb out and are greeted by the scientists and
crew. The Seeker is prepared for the second dive,
but suddenly the wind rises and the sea kicks up
into furious waves that crash over the deck of the
Maray. All hands rush to prepare for hurricane
force winds. There is no chance for the second
dive to begin. All day and all night the Maray
pitches on the stormy sea.
The next morning the wind has died and the sky
clear. You are now ready to dive again.
Turn to page 48.""")
def pg47(): #ending
print("""A helicopter is sent to pick you up and return
you to an air base for a flight back to the United
States. Newspaper reports indicate that the search
for Atlantis has been given up. Several months
later, however, a group of scientists get in touch
with you because they believe that Atlantis can be
found. They have put together another expedition
and want you to join it. You are tempted. Adventure into the unknown is what you like.
The End""")
input("click enter to exit")
stop()
def pg48():
print("""Again the Seeker is lowered over the side of the
Maray and slipsinto the ocean. Fish swim by peering cautiously at you in your metal shell.
The sunlight fades as you descend into the abyss.
You are headed for the giant canyon below that
might lead to Atlantis. When you reach the canyon
you switch on the Seeker's searchlight. Immediately you spot the round hole that appears to
be made by intelligent beings. Perhaps it leads to
Atlantis
Turn to page 9.""")
def pg50():
print("""You are dizzy from lack of oxygen and fatigue.
With your knife you slash away at the heavy brown
kelp thatsurrounds you. Bit by bit, you seem to be
getting free. Then suddenly you shoot up through
the last clinging pieces of seaweed and reach the
surface. You fire the special signal flare and the
crew of the Maray quickly spot you. Within a few
moments you are safely aboard, surrounded by
your friends. What a relief to be out of that nightmare world!
If you dive again the next day,
turn to page 67.
If you want to rest a few days and
make emergency plans, turn to page 68""")
def pg51():
print("""The three people of Atlantis sense your wish to
return to the surface. Instantly, they produce a
bubble-shaped capsule and put you inside.
"Farewell, earth person. May you live a long
and prosperous life."
You shoot up swiftly through the sea and break
out onto the surface near the Maray. The capsule
that protected you disintegrates upon reaching the
surface. Once aboard the Maray, you tell the crew
and the scientists about your adventure. They are
kind to you, but no one believes you. They think
you have imagined the world of Atlantis as a result
of being so deep for so long.
Back in the United States, you begin a television
tour telling about Atlantis. You write articles and a
book. You are paid a great deal of money for this
work. You are tempted to use this money for
another expedition.
If you use your money for
another expedition, turn to page 72.
If you decide to retire and
lead a life of ease, turn to page 74.""")
def pg53():
print("""The worst thing you could do would be to panic.
You relax and drift with the current which suddenly takes you upward. With your knife, you cut
through the kelp and are free. What a relief.
But no sooner do you get out of the kelp, than
you are caught in the vortex of a giant whirlpool!
If you try to swim out
of the whirlpool, turn to page 69.
If you dive into the vortex of
the whirlpool hoping to reach the bottom
and get out, turn to page 70.""")
def pg55():
print("""The three people lead you into an enormous
cavern. In the center of the cavern is a huge,
silver-colored machine. It isshaped like a long tube
with several round panels attached to one end.
They lead you inside. It is the most advanced
control room that you have everseen. Computers,
sensing devices, recording devices, monitors, and
a host of dials and panels fill the room. A strangely
shaped figure with a very large head and totally
blank eyes faces you.
"So, now you are in the control room of Atlantis. You see our secret. We landed on this planet
3000 years ago. We used our anti-matter device to
sink this continent beneath the sea so we could
escape from your people. You can have a most
pleasant and useful life here with us if you wish. All
you need to do is allow us to inject you with a
special serum to enable you to live down here. It is
up to you. On the other hand, if you do not wish to
be one of us, you will be held prisoner."
If you submit to the injection,
turn to page 71.
If you decline, turn to page 73.""")
def pg56():
print(""" "I wish to join the Nodoors," you tell your
guide. He leads you to the outskirts of the city.
"I must leave you now. Good luck." The
Nodoors send a greeting party that is heavily
armed. They are suspicious of you and believe that
you are a spy sent by the Atlanteans. They look
exactly like the Atlanteans, but they rarely smile.
"Come with us. You must be questioned.
Perhaps you will work for us."
For 3 days you are questioned and kept in a
small room without windows. These people are
not kind and you believe that you have made a
mistake. They ask you to help them spy on the
Atlanteans. They suggest that, as a spy, you could
pass freely between both groups.
If you decide to escape, turn to page 75.
If you decide to accept their offer,
turn to page 76.""")
def pg57():
print("""You decide to remain with the Atlanteans. Their
approach to life seemsideal. Time isspent in creating things to help life and not to destroy it. You
believe their leader is speaking the truth when she
tells of avoiding war and of not hating.
You are fascinated by this apparently ideal
world. You would like to stay and search out the
history of how Atlantis became what it is and what
caused the split between the Atlanteans and the
Nodoors. Yet, in your mind remains the hope of
escape so that you can go back to your own world.
If you decide to stay and spend
yourlife searching out the history and
secrets of Atlantis, turn to page 77.
If you decide to escape, turn to page 79.""")
def pg58(): #ending
print("""A large white lightshines down on you as you lie
on the operating table. Then you become unconscious. Pleasant thoughts, sounds, and pictures
occupy your mind. When you awake, you feel no
pain nor any real change. But, now you can
breathe underwater and join the Atlanteans in
their world.
For several weeks you explore the world under
the sea as you never have seen it before. Without
the heavy oxygen equipment on your back, you
feel a marvelous sense of energy and you glide
through a world of beauty. Your two guides have
become very good friends and they take you on
adventures in the deep, exploring the ocean bottom and getting to know the fish and other sea
creatures. It is a very exciting life indeed. You like
it, but you regret that you will never again know
the world above the sea.
The End""")
input("click enter to exit")
stop()
def pg59(): #ending
print(""""No, I refuse to have this insane operation. I
don't want to become a fish!"
The Atlanteans try to convince you that life with
them will be happy, useful, and long. Yet, you still
refuse. Sadly they give up their arguments and
spray you with a special mist that immediately
knocks you out. Several hours later you gain your
senses only to find that you are in an underwater
air tank where you breathe naturally. Your closest
neighbor is a horse who looks at you with sorrow
and understanding. The Atlanteans have built a
small apartment very much like the ones in the
world above the sea. People come by and look at
you and talk with you.
Maybe you have made a real mistake. They no
longer want you to join them in their world and
way of life. You refused their offer and now you
are a prisoner in a zoo.
The End""")
input("click enter to exit")
stop()
def pg60():
print("""It doesn't take you long to find the king. One of
his countless agents leads you to him. He is in a
small simple room with a strange light glowing
from the rounded ceiling.
"So, you have found your way here after all. Put
your mind at rest. I won't hurt you." The king's
booming voice startles you. He invites you to sit
down.
After several hours with the king, you find him to
be bright, friendly, and interesting. Maybe the Atlanteans are wrong about this person.
He offers you a chance to join his government.
He tells you that most people are lazy and selfish
and deserve to be ruled with power and command. He has been king for almost 1000 years
and he has survived because he is not afraid to be
tough. He wants you to be an advisor on his staff.
If you decide to accept the king's
offer and work for him, turn to page 80.
If you decide to refuse and
go back to join the other people,
turn to page 82.""")
def pg61():
print("""The problem is where do they escape to? The
king is in charge. He rules the world below the sea
and his spies are everywhere. The only answer is
to devise a plan to capture the king and put him in
prison.
The people are frightened. Some citizens tried
to revolt years before and are still in prison. The
king is smart and suspicious of everyone.
You suggest a plan to put on a festival with a
play. On a given signal the actors and the people in
the audience will rise up and seize the king. The
actors will be carrying real weapons, but no one
will suspect them because they are in the play.
The people like the plan. They ask you to become their leader.
If you accept their wish to
become their leader, turn to page 81.
If you decide to help them in
the planning, but also to escape from
this sad world, turn to page 86.""")
def pg63(): #ending
print("""There is one way out, you decide. Leave the
Seeker and try to reach the surface on your own.
You enter the airlock chamber which gives you
access to the ocean. With a quick push off, you
leave the Seeker and swim towards the surface. A
small, yellow life raft is part of your escape equipment. The surface of the sea is calm, but the Maray
is nowhere in sight.
For 2 days and nights you drift in the life raft
under hot sun and sharp starlight. At last a search
helicopter spots you. Finally you are safe.
The exploration of Atlantis will have to depend
on a new diver. Your eyesight has been damaged
by the strange force that immobilized the Seeker.
You career as an underwater adventurer is over.
The End""")
input("click enter to exit")
def pg64():
print("""The best plan is to wait until the Maray locates
you with sonar equipment. You can't signal the
ship because none of the Seeker's electronic
equipment is working. There is no sign of the
mysterious submarine. Perhaps it has left, now
that you have been chased away from the world of
Atlantis.
Looking out of the thick glass porthole, you see
a giant blue whale heading for you. It looks as
though the whale is going to ram you. Maybe the
other submarine has angered the whale and it is
seeking revenge on any craft near it.
Suddenly the whale hits you full force. The
Seeker is badly damaged. Water begins to trickle
in through the hatch cover. You must abandon the
Seeker. The whale now remains close to the
Seeker watching and waiting.
If you decide to try and escape,
turn to page 63.
If you try to hitch a ride on the whale,
turn to page 85.
If you don't know what to do,
turn to page 87.""")
def pg65():
print("""Why not go? Who would believe it? The center
of the earth! You push the control column forward
and dive deep. Soon there is no more water, just a
heavy gas that acts like water. You look at a world
of colors and drifting forms. You pass by layers of
rock and sand. Suddenly you sail into a gooey
mass which almost fouls the Seeker's propellers.
Then the Seeker's engine stops and you are pulled
along through the semi-liquid material by something like gravity or magnetism. You burst through
a thick elastic membrane and enter an area of giant
atoms. Electrons whirl around you at high speed,
but there is plenty of room to maneuver between
these fast-moving particles. The electrons are revolving around a small mass you know is called the
nucleus. You are able to avoid collisions with the
electrons. What a world! Maybe you are having
hallucinations.
If you continue on in this trip
to the center of the earth, turn to page 88.
If you try to turn back, turn to page 89.""")
def pg66():
print("""You face the fact that it is too dangerous to dive
into a deep hole that might lead to the center of the
earth. It is better judgment to return to the surface
and work out a plan of action.
You give one last look at the opening, check the
Seeker's instruments and head up to the surface.
Finally the Seeker breaks through into fresh air
and sunlight and you wait to be picked up by the
Maray.
Turn to page 32.""")
def pg67():
print("""You insist that you are all right and will dive
again the next day. The scientists try to convince
you that it is foolhardy to go down again so soon.
The captain of the Maray reportsthat a large storm
system is coming and the next day will probably be
the last day of diving for some time.
Against advice, you enter the Seeker, wave
farewell to all your friends and descend into the
deep. You feel tired but excited.
When you reach the bottom, you decide to
explore the ledge along the deep canyon.
Turn to page 6""")
def pg68():
print("""A violent storm is reported heading your way.
The captain decides to move the Maray to the
shelter of a nearby island harbor. It is too dangerous to remain where you are. Deckhands lash the
Seeker securely to the deck of the Moray and you
get underway.
The storm breaks before you can reach the
island harbor. The Seeker is torn loose and lost
overboard. The monitors aboard the Maray are
damaged by a frightful electric storm discharge.
You are all alive but there are no funds to replace
the damaged equipment. The expedition to Atlantis is over.
The End""")
def pg69():
print("""It is no use. The whirlpool has you in its grip.
You feel your arms and legs being torn in every
direction. There is no way out. Round and round
you go.
If you use your laser pistol to
blast a hole in the whirlpool wall,
turn to page 97.
If you continue to struggle,
turn to page 98.""")
def pg70():
print("""You decide that you can't swim out of the
whirlpool. There is only one thing to do. Dive deep
into the center.
You kick several times and hurl yourself into the
center of the whirlpool. Lights and colors dance
before your eyes. You lose all track of where you
are. You find yourself standing on the ocean floor.
You can look up through the center of the
whirlpool and see the sky more than 2000 feet
above you. It is a tiny patch of blue.
If you try to return to
the surface, turn to page 99.
If you set out to explore
this strange area, turn to page 100.""")
def pg71():
print("""Perhaps you are being foolish, but you decide to
join them. The injection is painless and you feel no
different than before. They lead you to a comfortable room where you all share a special tea in
celebration of your decision.
"You see, all living beings are basically the
same. Everything is connected in life. We have
come from a different planet in search of other
living beings. We have to be very careful about
taking new people to our planet. Some of your
people seek us out, just like you. We choose carefully."
You are amazed at what they say. A choice is
given to you. You can either journey with them
through time and space to their planet, or you can
remain in underwater Atlantis as a worker recording information about life on earth.
f you decide to travel
with them in space and time,
turn to page 90.
If you decide to stay in Atlantis
as a worker, turn to page 91.""")
def pg72():
print("""The only way to prove that you are not crazy is
to lead another expedition back to Atlantis. You
take all the money from the TV appearances and
articles and outfit a boat, hire a crew, rent the
Seeker, and set sail. Most people think that you are
out of your mind. You will show them.
Poised over the spot you so carefully marked on
the charts, you dive down in the Seeker. Again you
find the hidden grotto and the round metal panel.
The panel seems to seal off a passageway. It is
locked. You try to open it with the Seeker's drilling
arm, but it will not budge. It is frustrating to be so
close to the secret and yet so far from it.
Should you blast the panel with
the laser beam? Ifso, turn to page 93.
If you wait patiently to be
observed and asked in, turn to page 94.""")
def pg73(): #ending
print("""The idea of being injected with a serum and
joining them for the rest of your life is awful. You
must plan an escape.
When your captors are not looking, you slip
away and dash for the door of the space craft. You
fail to notice a laser beam guarding the exit hatch.
Stepping into the laser beam, you freeze in midstep. The Atlanteans gather round you sadly and
tell you that you will have to remain this way for the
earth equivalent of 23 years and 61 days until the
effects wear off. Then you will be given a second
chance.
The End""")
input("click enter to exit")
stop()
def pg74():
print("""You argue with yourself for several weeks about
setting out on a new expedition. Money is not the
issue. You fear that finding Atlantis will ruin it for
the Atlanteans. You believe that their civilization
must be protected. You decide to use the money
you have made to carry on research on space and
life on planets in other galaxies. Someday perhaps
you will meet the Atlanteans in space.
The End
If you don't like this ending,
turn to page 107.""")
def pg75():
print("""Escape will be difficult, but you decide that you
must get away from these people. The best plan is
to tell them that you want to accept their offer to
spy on the Atlanteans. They are of course happy
when you tell them that you will work for them.
"You see, the Atlanteans are jealous of us. We
must be on our guard or else they will invade our
area and capture us."
You don't believe the Atlanteans are at all jealous of the Nodoors, but you won't argue. They
take you back to the outskirts of their area, and you
leave to join the Atlanteans. Once back with the
Atlanteans, you ask them to allow you to live with
them. You know that you will never be allowed to
leave their underwater world, but there is always
the hope for escape. It could be a good life.
The End""")
def pg76():
print(""""Ok, I'll do it," you say. "I'll join you and spy on
the Atlanteans for you. Who knows, maybe they
aren't as bad as you think."
The Nodoors are delighted that you will help
them. They give you a room in a large building
where most of them live. It is grey and forbidding,
more like a prison than anything else. That night
when all are asleep, you sit sleepless and realize
that you are caught in a trap of your own making. It
comes to you that the Nodoors are from a different
planet and are unhappy outcasts. The Atlanteans
want nothing to do with them. You chose the
wrong side.
The End
If you don't like this ending,
turn to page 108.""")
def pg77():
print("""Maybe you can learn from the Atlanteans how
they achieve such happinessin their lives. You will
seek out their history.
When you announce your decision to stay, you
are treated with kindness and friendship. You explain that you would like to help in their underwater food production.
Atlantis was an advanced civilization thousands
of years ago. The citizens nourished their peaceful
thoughts and plucked out their hateful thoughts as
one would tend a garden. Their minds became a
rich and dazzling universe, clear and unbounded.
You have so much to do, helping with sea plants
and studying their history that you soon forget the
Seeker.
The End""")
def pg79():
print("""When you get a chance and everyone is doing
other things, you dash for the tunnel exit and make
it out into the water. No alarms sound. No one
chases you. It is strange; they said they wouldn't
allow you to return to the world above the sea.
Why are they letting you escape?
You swim toward the surface; then you black
out. It is too deep. No one could survive the pressure and lack of oxygen.
But a miracle has happened because you suddenly find yourself hacking
away at brown seaweed that surrounds you and
you are just a short way from the surface.
Turn to page 50.""")
def pg80():
print("""An advisor to a king! What a chance. Maybe the
king has ruled so long that he is out of touch with
the people. Perhaps as his advisor you can help
the people get what they want. You don't believe
that people are lazy and selfish. The king just needs
a new point of view.
You are appointed the king's special advisor on
problems of research on food and shelter. You
immediately call general meetings of all the people
to discuss the food program and the work
schedules. The king is so glad to have someone
else take over the problemsthat he leavesit in your
hands entirely. He gives you land and a large
salary. You set up new programs and schedules.
The people are involved in the planning and the
work. You listen to their complaints and their
ideas. Life under the sea is rich and full. The
people are hard working and good. It was a wise
decision to remain.
The End""")
def pg81():
print("""You do not wish to lead a revolt but the people
need you. You organize the play, and the king is
pleased to have his people involved in a project
that keeps them busy and happy. The people can't
wait for the day when they can put the king in
prison and make their own decisions.
The night of the play, the theater is filled, and
everyone waits for the king to appear. But there is
a delay. The crowd grows nervous. Then a messenger from the king runs into the theater and
announcesthat the king has had a serious attack of
brain fever. He may not live.
You wonder whether the king is really ill or
whether he has found out about the plot against
him. The people are confused and do not know
what to do. They turn to you and you tell them to
go on with the play.Just then, a squad of the king's
soldiers enter the theater. They are headed for
you.
If you allow them to capture you,
turn to page 116.
If you try to escape, turn to page 117.""")
def pg82():
print("""Advisor to a mean king? Not a chance! You tell
him that you want nothing to do with a tyrant who
doesn't believe in people. You tell him to his face
that the people are unhappy and angry. He laughs
and tells you to go back to them if you wish. He
warns you that the people are complainers, not
workers.
Once back with your new friends, you discuss
how to overthrow the king and his henchmen. You
hold secret meetings and work out a plan. But on
the day of the overthrow, someone discovers a
leak in the volcano wall of the underwater world.
The entire civilization is in danger. All thoughts of
revolt are forgotten. The Atlanteans must stop the
sea from crashing in on them. Everyone works for
a common purpose. Survival is the goal.
If you decide to work with them
in this time of disaster, turn to page 112.
If you decide to take advantage of
this emergency to escape, turn to page 114.""")
def pg85(): #ending
print("""People ride dolphins, and you have met scuba
divers who reported they held onto the flukes of
whalesforshort rides. Itsounds crazy, but this may
be your only way of escape. You leave the Seeker,
swim to the whale, and grab its fluke. With a
smooth powerful movement, the giant mammal
begins to swim to the surface. You have trouble
holding on. Then the whale breaksthe surface and
lies there filling its lungs with air. You quietly swim
away.
You drift for 2 or 3 days, dozing and waking
comfortably. You stay warm in your insulated sea
suit and its special air packs keep you afloat. You
are hungry and thirsty, but unharmed by the time
the search helicopter spots you bobbing in the
waves.
The End""")
input("press enter to exit")
stop()
def pg86(): #ending
print("""It is their world, but you are willing to help them
with the planning for the overthrow of the king.
You want no real part in the revolt.
The planning requires choosing new leaders
and setting goals for the people. You almost decide to join them in the actual revolt, but you really
want to get back to your own world. Once the
revolt is underway, you hope to slip away and
return to the Seeker for a quick escape to the
surface of the ocean.
The day of the revolt, you can't resist the excitement of the Atlanteans'bold enterprise, and
you decide to stay with them and help in any way
that you can. The endless planning and training
pays off. The carefully selected band of men and
women easily capture the king and his guards. The
revolt has succeeded without shedding a drop of
blood and the people celebrate for days.
The Atlanteans treat you as if you are one of
them, and, for the first time, you feel that you are.
The End""")
input("Press enter to leave the program")
stop()
def pg87(): #ending
print("""You admit that you just don't know what to do.
The whale is frightening looking and you don't
have any escape plans. So you wait and watch and
listen.
After what seems a long time, but is probably
just a few minutes, the mysterious submarine returns, attaches a cable to the Seeker, and pulls you
up to the surface. Then the submarine vanishes
under the wavesleaving you to wait for the Maray.
The End""")
input("click enter to exit")
stop()
def pg88():
print("""The electrons whirl about at dizzy speeds and
you continue until you get to a spot where your
instruments indicate that there is no time. The
clocks stop, the speed indicator stops, your heart
stops, and yet you are alive. Every sense in your
body seems more alive than ever before. You hear
beautiful music and see lights that you feel and
taste as well. Peace and well-being fill you.
You become aware of other beings close to you.
No one has entered through the only hatch and yet
there are other presences in the Seeker. Turning
around, you see three Atlanteans. Then you feel
that the Seeker has become just a thought and that
the people from Atlantis have entered your mind
and are aboard the Seeker. You try to enter their
thoughts, but they tell you that you have not journeyed far enough yet to be able to become a
thought-traveler.
If you try to turn back from
thisstrange world, turn to page 95.
If you decide to travel in
thought-time-space, turn to page 96.""")
def pg89(): #ending
print("""No, you will not dive down toward the center of
the earth. Once through the thin outer layer of the
earth, you know that the regions beneath change
from solid to molten and then to a hard core. At
least that is the theory given by the scientists. You
couldn't possibly survive such a journey. Anyway,
you think that your sonar gear is probably not
working correctly. The hole is deep, but you don't
believe that it really goes all the way to the center of
the earth. Caution is your approach. You go back
to the surface to consult with the scientists aboard
the Moray.
The scientiststell you that their instruments have
been damaged, perhaps by an approaching storm,
and they too, are cautious. They decide to move
the Maray away from the site of the mysterious
hole. The expedition retreats and you know your
chance to discover Atlantis has slipped away.
The End""")
input("click enter to exit")
stop()
def pg90():
print(""" "I will go with you. I want to see other parts of
the universe."
"Congratulations. You will not regret this. We
are ready to depart."
They take you to a small room and three of them
stand with you under a beam of intense light. You
feel a rush of speed, and yet you are not moving.
You feel as though you have traveled hundreds of
thousands of milesin space. You rush past the sun,
past and through the Milky Way, and on into other
galaxies. Yet, you feel asthough you are stillstanding in the same spot.
Then you are on the planet Aygr where the
Atlanteans came from. It is a world of fantastic
shapes and strange plants. The city gleams like a
thousand search lights. The shapes that must be
their buildings are pure light pulsing with energy.
Nothing is hard or sharp. Everything is light. You
see no people, just forms of brighter light that
move. Suddenly, some of the moving forms
change into Atlanteans.
"Our bodies are not important. It is our energy
that isimportant. You can see usin our body forms
if you wish, but we only use them to communicate
with people like you. You may choose to remain as
you are or accept transformation."
If you decide to stay in
your body form, turn to page 101.
If you decide to
be transformed into an energy shape,
turn to page 102.""")
def pg91():
print("""You have had enough adventure for now.
Travel to another planet in a different galaxy
sounds like more risk than you wish to take. Besides, you can always go later.
You tell the people that you wish to stay and
work in their society. Perhaps your knowledge of
the sea can help them. They discuss your case very
seriously for several days. When they are through
talking, they offer you a choice of jobs in Atlantis.
You may become a farmer or a musician.
If you decide to become an
underwater farmer, turn to page 103.
If you decide to become
a musician, turn to page 104.""")
def pg93(): #ending
print("""You'll try to blast the hatch right off its hinges.
You have the power. Your finger presses the red
button that fires the laser cannon. A blinding flash
erupts immediately. But the hatch remains firm.
You fire again and again and again. Each time the
Seeker is rocked by the force of the laser cannon.
The reflected energy is damaging to your craft.
You continue to fire the cannon, holding your
finger on the button.
Then there is a blinding flash inside the Seeker
itself. The laser cannon has exploded. You and the
Seeker are destroyed instantly. The hatch remains
closed.
The End""")
input("click enter to exit")
stop()
def pg94():
print("""It is never good to use force unless you are
attacked and must defend yourself. You refuse
even to consider using the laser cannon; it might
kill people and would certainly destroy any chance
for friendship. You decide to wait patiently and
hope that you will be noticed and invited in.
For six hours you sit quietly and wait for some
sign. A green glow comes from the area ahead of
you. It bathes the Seeker in a gentle light. The
hatch door opens. Three figures emerge and
beckon to you to follow them.
If you follow, turn to page 105.
If you refuse to follow them,
turn to page 106""")
def pg95(): #ending
print("""This is too much for you. It is like a nightmare
and you decide to turn back. But going back is
much harder than you expected. The electrons
whirl closer and closer to you as though they were
guards keeping you from leaving. It is difficult to
guide the Seeker in this maze of atoms. The instruments are useless now.
The figures of the Atlanteans disappear. Suddenly, you are caught in
the elastic membrane that almost stopped you
before. It sticks to the Seeker, holding you back.
You want to be free and return to the world you
have known all your life.
You lose consciousness and wake up several
hours later in your sea suit floating above the hole
in the ocean floor. The Seeker is gone. You're
dazed: did you dream the whole thing? Slowly you
return to the surface, but the Maray has disappeared. You can't decide how much time has
elapsed. You realize that your crew must think you
are lost forever and you know they are right. The
waves rock your unresisting body back and forth
as you float alone in the vast sea. You feel your
strength slowly draining away.
The End""")
input("click enter to exit")
stop()
def pg96():
print("""A thought traveler! You realize that people do it
all the time in day dreams. Of course, you want to
be a thought traveler, but how?
The Atlanteans speak softly and tell you that all
things are the sameโ past, present, future are all
the same. It simply requires you to concentrate
and put your thoughts where you wish them to be.
You try, and amazingly you are rapidly rushed
through time to the day you were born, then to the
day you made your first deep-sea dive. Your mind
flies from one time in your life to another. But
when it comesto the future, you meet a blank wall.
You can't seem to travel into the future.
"Why can't I travel ahead in time," you ask the
Atlanteans.
"Be patient," they reply. "All in good time."
Suddenly you whirl through time into the outer
reaches of the universe where you can actually feel
the light going through you. You cast no shadow.
A sense of peace fills you.
If you decide to drop out of
thought travel and return to earth
life, turn to page 110.
If not, The End.""")
def pg97(): #ending
print("""You have a laser pistol that you carry for
emergencies. You blast a hole in the whirlpool wall
and dive through it. Facing you is a school of fish
who are puzzled by this strange intruder. Behind
them lurks the form of a shark. You swim toward
the surface slowly and the shark vanishes into the
deep.
The Maray is nowhere in sight.
You are wondering how long you'll be waiting when a loud splashing sighing sound startles you. A huge whale has
surfaced and lies nearby spouting and sucking in
great noisy draughts of air. It take you a good half
hour to swim to the enormous creature. It pays no
attention to you. You climb onto its tail and crawl
on hands and knees toward the highest point of its
back. It's like creeping up a gigantic grey rock.
From your vantage point on top, sure enough,
you can see the Moray and the tiny glint of binocular lenses reflecting in the sun. The Maray crew is
watching the whale. You wave, feeling certain they
have seen you. It won't be long before they come
to collect you.
The End""")
input("click enter to exit")
stop()
def pg98(): #ending
print("""You faint, and when you come to, you are
floating on the surface of the ocean. There is a
heavy ocean swell and the sun beats down on you.
The whirlpool must have stopped as quickly and
mysteriously as it began. You feel dizzy and
exhausted and you move gently to make sure you
haven't broken any bones. As you move your
head slowly inside your helmet, you feel an intense
pain shooting across your right temple. You have
to lie very still then and gradually your ears pick up
the thrum of the search helicopter. You don't dare
move to look, but as the minutes go by, the thrum
gets louder and slowly disappears. The helicopter
has passed over you. It won't return this way. The
pain in your temple increases. You begin to lose
consciousness.
The End""")
stop()
def pg99(): #ending
print("""The walls of the whirlpool look like solid ridges
sloping upwards to the surface. The water is rushing so fast that the center looks absolutely calm.
You wonder if perhaps you could swim up through
that calm. It's worth a try, and you set off. Before
you can tell if you're making any progress, the
whirlpool reverses and instead of whirling down, it
whirls up and catapults you out of the ocean and
into the air. You fall back onto the surface of the
ocean close to the Maray. Although you are
stunned by the fall, you quickly gain your senses
and are picked up by the ship. Of course no one
believes your story, but then even you think it is
almost too fantastic to have happened.
The End""")
input("click enter to exit")
stop()
def pg100():
print("""The ocean floor has a small metal hatch on it.
You pull with all your strength but it will not open.
You rest for a moment and look through the wall of
watersurrounding you. Two fish stare back at you!
It's asthough you are in an aquarium for the fish to
look at.
You don't hear the hatch open. A voice commands you to enter. With fear and caution you
walk down a corridor that leads to a small room.
Three people meet you.
Turn to page 55.""")
def pg101(): #ending
print("""You just can't give up your body. It might be all
right for the Atlanteans to move about as pure
energy, but you have not reached a point where
you are willing to risk what you are for what they
are.
It isstrange wandering about with bright glowing
blobs of energy moving with you. They ask you to
give talks about life on earth as you know it, and
you agree. For two years you meet with the Atlanteans in their energy forms and talk about earth
and how people live and what they do. The Atlanteans are interested in all aspects of earth life: the
technology, politics, wars, and religion.
You ask them why, but they never give you a
direct answer. Then one day you look down at
yourself and you only see bright, glowing energy.
With horror you realize you have become one of
them.
The End""")
input("click enter to exit")
stop()
def pg102(): #ending
print("""You are in the Atlantean world; why not become like an Atlantean? Looking down at your
hands, you see them gradually begin to glow with
a warm, yellow light. Little by little, the glow travels
up your arms and legs until suddenly you have no
body left. You are a glowing energy form. You feel
a sense of freedom and happiness that you have
never known before. You can float, or fly, or zoom
anywhere you want to. No wallsstop you; you just
melt through them. You don't need food or rest.
You can travel through time, and you can travel
instantly back to earth in your energy form.
You feel that this is the way you want to be.
The End""")
input("enter to exit")
stop()
def pg103(): #ending
print("""Farming under the sea is a job that you enjoy.
Outside Atlantis, there are fields of sea plants that
are worked on just like gardens above the sea.
Atlanteans go out each day and harvest the plants,
take care of the fields, and chase away the fish that
love to nibble on the growing plants. Then there
are fish pens to work on. There you feed and tend
the fish until they are needed for food. Farming
under the sea is beautiful and it is much easier than
you had imagined. Danger lurks, though, in the
form of sting rays, slender sea snakes, and occasional sharks. You have to be on your guard at all
times.
The End""")
input("click enter to exit")
stop()
def pg104(): #ending
print("""A musician in the world of Atlantis. Who would
believe it? You are asked to choose an instrument
to play. You examine water lutes,sea drums,shark
bone flutes, and a wide range of electronic instruments.
You choose one of the electronic instruments, but it makes no sound at all. You are told
that it plays music that people feel rather than hear.
What a world you're living in! Who would believe
in music that is not heard? Gradually you learn to
feel the different notes with parts of your body:
your thighs, chest, temples, and fingertips. Your
interest in this new way of sensing music grows
with each day. You master this new art form. You
become their greatest musician.
The End""")
input("click enter to exit")
stop()
def pg105(): #ending
print("""These people lead you to a control room. There
you meet the commander of an underwater scientific center that is conducting secret research into
life underneath the sea. They inform you that it
was a good thing that you did not use your laser
cannon, because they have anti-laser devices that
would have blown you and the Seeker to pieces.
After a pleasant meal and a tour of the deepwater lab, you are sent back to the Seeker for a
return journey to the surface. You are told never to
return again; if you do, you will be kept a prisoner
for the rest of your life.
The End""")
input("click enter to exit")
stop()
def pg106(): #ending
print("""When you refuse to follow them, they take out
small hand-held hypnotizers that put you into a
deep trance. You are led through a long tunnel
into a large underwater lab. Three military technicians come up to you and break the trance.
"You have stumbled into a secret military base.
We're developing too many secret plans to risk
being discovered. You will remain our prisoner."
There is no escape.
The End""")
input("click enter to exit")
stop()
def pg107(): #ending
print("""You argue with yourself for weeks. Then you
decide to go back to Atlantis. You are in such a
hurry to return that you hire a small, fast hydrofoil
craft to take you to the spot in the ocean where
Atlantis is. Once reaching the spot, you intend to
make a dive with just scuba gear! You know a
2000 foot dive is impossible. But you don't care;
you feel you must make the attempt.
A storm rips the sea for six days and when it
clears you prepare to dive. Just as you slip into the
water, you look up into the sky and high above the
clouds you see the sparkling city of Atlantis. No
dive is necessary.
The End""")
input("click enter to exit")
stop()
def pg108(): #ending????
print("""During the night, you are awakened by the
sound of voices talking quietly. Listening, you
realize that a group of Nodoors is planning an
escape. They want to join the Atlanteans. They
believe that life in Atlantis can be better for them.
You join them and listen to the stories of fear and
darkness. They seek light and friendship. It sounds
simple, but nothing is easy.""")
def pg109(): #ending
print("""Suddenly the door bursts open. Three guards
armed with special weapons rush in. They fire the
weapons and in a flash of brilliant light you and
your companions are vaporized.
The End""")
input("click enter to exit")
stop()
def pg110(): #ending
print("""Over 1000 years of thought travel later, you are
called into the main thinking room. You are told
that you may now return to earth life. You have
doubts about going back, but you are curious to
see what changes have occurred while you were
living in Atlantis.
What a sight greets you as you circle earth at an
altitude of 1000 feet! The great cities of the world,
New York, London, Paris, and Hong Kong are
overgrown with vegetation. The roadsleading into
the cities are barely visible. But you see signs of
new settlements. There are clusters of buildings
spread out in the countryside. You don't see any
smokestacks. There are few roads and no cars.
The people live a simple life providing themselves
with food, shelter, and clothing. You wish to join
them.
The End""")
input("enter to exit")
stop()
def pg111(): #ending
print("""One day your friendstell you that you can return
to earth if you wish. You consider it carefully and
decide that because of your thought traveling ability, the life you now lead is what you want. You
decide to stay where you are forever.
The End""")
input("click enter to exit")
stop()
def pg112(): #ending
print("""Years ago the Atlanteans had worked out
emergency procedures, but most people had forgotten them. One old person remembers where
the emergency instructions and equipment were
kept.
You and the Atlanteans work without stop for
72 hours pumping out the flooding waters and
building a special retaining wall around the volcanic crack. Finally the last pump is shut off. You
are all exhausted, but you've won in your battle
against the sea.
The End""")
input("click enter to exit")
stop()
def pg114(): #ending
print("""With everyone worried about the sea crashing
in, no one will notice you if you try to escape. You
run down a long, little-used corridor that leads to
the sea. The exit door is heavy and rusty from not
being used. You push with all your might, and
finally it swings open into an airlock to the open
water. You push the emergency release button
and shoot out into the water. The Seeker is where
you left it, and once inside, you head for the surface where the Maray waits for you.
The End""")
input("exit to leave")
stop()
def pg116(): #ending
print("""It is uselessto try to escape the soldiers. You are
surrounded. They take you to the king, and he
sadly tells you that you are just like all the rest. He
can't trust anyone. He will have to decide what to
do with you and in the meantime he throws you
into the dungeon.
The End""")
input("click enter to exit")
stop()
def pg117(): #ending
print("""How can you escape? The soldiers are coming
after you. You yell as loud as you can and everyone in the theatersurrounds you, forming a barrier
to the soldiers. The soldiers stare at the people all
around them, hesitate, and then quickly leave.
They know that the odds are too great to win such
a fight.
The people cry for the revolt to go on. The
crowd leaves the theater and heads to the king's
quarters. All along the route people join you and
even the king's soldiers begin to join the crowd.
You and the people are free; the king is put in
prison. The revolt is a success.
The End""")
input("click enter to exit")
stop()
|
2341dbe3fba41f18b1941a1f75a1a936ab7f4256 | wanglouxiaozi/python | /Dictionary/demo.py | 422 | 3.84375 | 4 | #!/usr/bin/env python2
# -*- coding: UTF-8 -*-
def test(dict1, list1):
dict1.pop('name')
list1.pop()
print dict1, list1
def test2(str1):
str1 = 's'
print str1
def __main():
dict1 = {'name': 'allen', 'age': 24, 'sex': 'm'}
list1 = ['nihao', 'shanghai']
print dict1, list1
test(dict1, list1)
print dict1, list1
str1 = "hello world"
print str1
test2(str1)
print str1
if __name__ == '__main__':
__main()
|
a1ea0303fe594fde08ca41c94050dbf9f5d2d3ad | abhinay-b/Leetcode-Submissions | /accepted_codes/Merge_Intervals/Merge Intervals_285451343.py | 727 | 3.53125 | 4 | class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
return intervals
# sort based on the start of the interval
intervals.sort(key=lambda x: x[0])
res = []
idx = 1
temp = intervals[0]
while idx < len(intervals):
if temp[0] <= intervals[idx][0] <= temp[1] or intervals[idx][0] <= temp[0] <=
intervals[idx][1]:
temp[0],temp[1] = min(temp[0],intervals[idx][0]), max(temp[1]
,intervals[idx][1])
else:
res.append(temp)
temp = intervals[idx]
idx += 1
res.append(temp)
return res
|
611c1b9266d7acc8b646ade3a58378f3d08dec93 | yif042/leetcode | /Python3/no350. Intersection of Two Arrays II.py | 494 | 3.625 | 4 | class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if nums1 is None or nums2 is None:
return None
long, short = (nums1, nums2) if len(nums1) >= len(nums2) else (nums2, nums1)
long.sort()
res = []
for i in short:
if i in long:
res.append(i)
long.remove(i)
return res
|
3e45fd58649d4ec9c16bcf24b426c8a04d0825d0 | Sylphy0052/TownDiceGameForPython | /src/landmark.py | 1,006 | 3.515625 | 4 | from enum import Enum
class LandmarkType(Enum):
TrainStation = 1
ShoppingMall = 2
AmusementPark = 3
RadioTower = 4
class Landmark:
def __init__(self, name, cost, player):
self.name = name
self.cost = cost
self.player = player
def play(self):
pass
def get_name(self):
return self.name
def get_cost(self):
return self.cost
class TrainStation(Landmark):
def __init__(self, player):
super().__init__("Train Station", 4, player)
def play(self):
pass
class ShoppingMall(Landmark):
def __init__(self, player):
super().__init__("Shopping Mall", 10, player)
def play(self):
pass
class AmusementPark(Landmark):
def __init__(self, player):
super().__init__("Amusement Park", 16, player)
def play(self):
pass
class RadioTower(Landmark):
def __init__(self, player):
super().__init__("Radio Tower", 22, player)
def play(self):
pass
|
407493608416dc370b48d585dd1a6699e8e73a71 | 0n1udra/Learning | /Python/Python_Modules/Matplotlib.py | 13,000 | 4.03125 | 4 | # imports all functions of pyplot from matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
from mpl_toolkits.mplot3d import axes3d
import matplotlib.style as mstyle
import matplotlib.animation as manime
import random as rd
import numpy as np
# creates plot data
#x = [j for j in range(0,101)]
#y = x
x = [j for j in range(0,101)]
y = [rd.randint(-50,50) for i in range(0,101)]
print('Default Data')
print("X Data: ", x)
print("Y Data: ", y)
def plot1():
plt.plot(x, y)
# creates a graph, and plots down the data, is connects plots automatically
plt.show()
# shows the graph
# this well not show the markers to indicate the plot locations, just line.
# basic plot
def plot2():
plt.plot(x, y, label='Plot2', color='red', marker='X', markeredgecolor='blue')
# 1. 2. 3. 4. 5.
# 1) data. 2) sets the label of plot, only shows with legend().
# 3) sets color of plot, line, bar. 4) sets marker for plots, X/O/+ etc, without this you can't see the plots
# 5) sets the edge color of the marker, the inside well be what 'color' is, which is red right now
plt.show() # shows graph
# More Options
# s=50 -- sets size of markers
# plot(x,y, 'ro') / 'k-' -- r or k is the color, o or - is the marker. just a quicker way to do color='red', marker='o'
def plotTypes():
fig = plt.figure('bars')
# this creates a new graph, a new windows, separate from the bar graph.
ax1 = fig.add_subplot(111)
# creates a empty plot
ax1.bar(x, y, color='r', label='Bar1', edgecolor='b') # makes bar graph with data
# 1. 2. 3. 4.
# 1) data. 2) fill color of bars. 3) label.
# 5) sets color of edges of the bars.
# histogram
fig = plt.figure('hostgram')
ax2 = fig.add_subplot(111)
ax2.hist(x)
# scatter
fig = plt.figure('scatter')
ax3 = fig.add_subplot(111)
ax3.scatter(x, y)
# stack plot
fig = plt.figure('stack plot')
ax4 = fig.add_subplot(111)
ax4.stackplot(x, y)
plt.show()
# shows different types of graphs and plots
def subplot2Grid_1():
fig = figure()
# creates new figure
ax1 = subplot2grid((1, 1), (0, 0))
# creates new plot graph, same as plot(x,y), but more options
ax1.plot(x, y, label='PLOT')
# calls plot with the ax1 settings
### Labels and Ticks ###
## Ticks ##
for labels in ax1.xaxis.get_ticklabels():
# for every x axis ticks do this
labels.set_rotation(45)
# rotate all of the x axis ticks, works with y axis >
for labels in ax1.yaxis.get_ticklabels():
labels.set_rotation(45)
# rotates y ticks by 45
ax1.tick_params(axis='x', colors='g')
ax1.tick_params(axis='y', colors='r')
# tick options
#ax1.set_yticks([0, 10, 20, 30, 40, 50])
# sets the tick marks for y axi
# this well set this permanently, if zoom to far out or in it'll stay at these.
## Labels ##
xlabel("X Label!")
# shows x axi name
ylabel("Y Label!")
# shows y axi name
title("This is a Graph!")
# gives title to graph
# Label Appearance #
# X and Y axi label rotation
ax1.xaxis.label.set_rotation(10)
ax1.yaxis.label.set_rotation(10)
# X and Y label color
ax1.xaxis.label.set_color('g')
# colors x label green
ax1.yaxis.label.set_color('r')
# colors y label red
### Graph Look ###
ax1.fill_between(x, y, alpha=0.3, facecolor='r')
# this well fill the graph basically, with some transparency
# you can just use this without plot() and it'll still show the data, just not a big line
# you can't label with this either. have to use a blank plot()
## Spines ##
ax1.spines['left'].set_color('c')
# changes left spine to cyan
ax1.spines['left'].set_linewidth(5)
# changes thickness of line
ax1.spines['right'].set_visible(False)
# hides right spine
ax1.spines['top'].set_visible(False)
# hides top spine
## Grid ##
major_ticks = np.arange(0, 101, 10)
minor_ticks = np.arange(-50, 51, 10)
# sets tick marks range
ax1.set_xticks(major_ticks)
ax1.set_xticks(minor_ticks, minor=True)
ax1.set_yticks(major_ticks)
ax1.set_yticks(minor_ticks, minor=True)
# shows tick marks
grid(True, which='both')
# enables grid, for more go to looks1()
ax1.axhline(1, color='r', linewidth=1)
# shows red line at Y 1
subplots_adjust(left=0.09, right=.95, bottom=.15, top=.9, wspace=0.2, hspace=0)
# 1. 2. 3. 4. 5 6. 7.
# 1) sets the graph appearance.
# you would use this if you need more space for the labels,
# because resizing the window won't give more room, it'll just make the graph bigger
legend()
show()
# how to use subplot2grid
def candleSticks1():
pass
# candlestick graphs
def Style():
print(matplotlib.__file__)
# prints matplotlib file location
print(style.available)
# prints available styls
style.use('DT_dark_background')
# uses style
grid(True)
# enables grid
plot(x,y, label='test')
# creates plot
legend()
show()
# theming/stylizing your graphs
def Anime():
mstyle.use("DT_dark_background")
# style of graph
fig = plt.figure()
# new figure
ax1 = fig.add_subplot(1,1,1)
# creates ax1 subplot
def animate(i):
# a functions that reads from a file and refreshes the xs/ys list every 1 second
graph_data = open("sampFile.txt", "r").read()
# opens file to be read
lines = graph_data.split('\n')
# splits it by new line
xs = []
ys = []
# creates blank lists
for line in lines:
if len(line) > 1:
# check if the line is empty or not
x, y = line.split(',')
# if not, splits it by comma
xs.append(x)
ys.append(y)
# appends to lists
ax1.clear()
# clears everything
plt.grid(True)
# shows grid. put this AFTER clear, if not it'll clear the hgrid too
ax1.plot(xs,ys, marker='X', label='1sec Iterval')
# plots out data
plt.legend()
# shows legend
ani = manime.FuncAnimation(fig, animate, interval=1000)
# uses figure, calls function with plot() and clear() and with data
# then does this for ever every 1second, which is why you need clear()
plt.show()
# not really animation, this well just keep updating the graph.
# so if you open up the data file and change the data, it'll update right away. no moving things though :(. but it's on the same principle
def Text():
### Setup ###
fig = plt.figure()
# figure
ax1 = fig.add_subplot(1,1,1)
# ax1
ax1.grid(True)
# enables grid
ax1.plot(x,y)
# plot
### Text ###
font_dict = {'family' : 'verdana', # sets font family to serif
'color' : 'red', # sets color to red
'size' : 20,
'style' : 'italic',
'weight' : 'bold'} # well size...... IT'S THE SIZE!!! duh.
# sets the configuration of fonts for anything that prints out text, labels, etc
print("X Label Axi: ", x[50])
print("Y Label Axi: ", y[50])
ax1.text(x[50]-8, y[50]+ 1, "hi", fontdict=font_dict, withdash=True)
# 1. 2. 3. 4.
# 1) coordinates of text, with a little offset so the arrow won't hide it.
# 2) text. 3) calls font_dict for text properties
# 5) ...
# prints out text at X10 Y5, that says hi, with settings from font_dict
text_opt = {'boxstyle' : 'round',
'pad' : .5,
'facecolor' : 'cyan',
'edgecolor' : 'green',
}
arrow_props = {'facecolor' : 'blue',
'edgecolor' : 'yellow'}
plt.annotate('hi', xy=(x[50],y[50]), xytext=(1.03, 0.9), textcoords='axes fraction', bbox=text_opt, arrowprops=arrow_props)
# 1. 2. 3. 4. 5. 6.
# 1) text. 2) coordinates for arrow. 3) % offset of annotation text from coordinates (2.)
# 4) gets the coords from x/y in thr 50th place, and that's where the arrow well point, it'll be different every time you run it.
# 5) calls text_opt for the properties of the text 6) calls arrow_props dict for properties of arrow.
plt.show()
# shows everything
# show text and annotate on graph
def fourPlots():
fig = plt.figure()
# new window to graph
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 3)
ax3 = fig.add_subplot(2, 2, 2)
ax4 = fig.add_subplot(2, 2, 4)
# creates 4 new subplots to graph on to
# (row, column, plotNum)
ax1.plot(x,y)
ax2.plot(x,y)
ax3.plot(x,y)
ax4.plot(x,y)
# plots data on to each subplots, they all have the same data in the example
plt.show()
# show more plots with subplot
def sixPlots():
ax1 = plt.subplot2grid((6,1), (0,0), rowspan=1)
ax2 = plt.subplot2grid((6,1), (1,0), rowspan=1)
ax3 = plt.subplot2grid((6,1), (2,0), rowspan=1)
ax4 = plt.subplot2grid((6,1), (3,0), rowspan=1)
ax5 = plt.subplot2grid((6,1), (4,0), rowspan=1)
ax6 = plt.subplot2grid((6,1), (5,0), rowspan=1)
# creates six plots stacked on top of each other
# ((rows, columns), (startingRow, startingColumn))
# rowspan/columnspan is how much space should the plot take up
ax1.plot(x,y)
ax2.plot(x,y)
ax3.plot(x, y)
ax4.plot(x, y)
ax5.plot(x, y)
ax6.plot(x, y)
plt.show()
# shows six plots using subplot2grid
def Legend():
plt.plot(x,y, label="plot1")
plt.plot(y,x, label='Reverse plot')
leg_props = {'size': 8 # font size
}
plt.legend(loc=10, ncol=2, facecolor='r', prop=leg_props).get_frame().set_alpha(.1)
# 1. 2. 3. 4.
# 1) sets location of legend, 1-4 corners, 5-9 sides, 10 center
# 2) sets limit on colums. 3) sets face color. 4) gets some properties from dictionary.
# 5) sets alpha of background
plt.show()
# customize the legend
def ThreeD():
fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
# sets ax1 to 3d projection
mstyle.use('dark_background')
# change style
x = range(1,11)
print("X: ", x)
y = [rd.randint(0,11) for i in x]
print("Y: ", y)
z = [rd.randint(0,11) for j in x]
print("Z: ", z)
# creates random data to plot
ax1.set_xlabel("X Axi")
ax1.set_ylabel("Y Axi")
ax1.set_zlabel("Z Axi")
# names the x/y/z label
ax1.plot_wireframe(x,y,z, label='Random Data')
# plots data with a label
ax1.scatter(x,y,z)
# creates scatter plot, but layers on the wireframe.
fig2 = plt.figure()
# creates new figure, so makes a new windows
ax2 = fig2.add_subplot(111, projection='3d')
# new subplot with 3D projection
ax2.set_xlabel("X Axi")
ax2.set_ylabel("Y Axi")
ax2.set_zlabel("Z Axi")
# names the x/y/z label
x1 = np.ones(10)
y1 = np.ones(10)
z1 = range(1,11)
# this is the height of the bars, so bar 1-10 well have height 1-10
ax2.plot([],[], color='r', label='BARS!!')
# have to make a blank plot because for some reason bar3d won't take label
ax2.bar3d(x,y,z, x1, y1, z1, color='r', edgecolor='c')
# shows bar3d plot, the bars will be red with cyan edges
plt.legend()
plt.show()
# 3D plots, 3D bar-graph and 3D plotting
def betterWF():
x,y,z = axes3d.get_test_data()
# gets test data from axes3d module
print("\nWireframe Test Data")
print("X Data: ", x)
print("Y Data: ", y)
print("Z Data: ", z)
# prints out test data
fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
ax1.plot_wireframe(x,y,z, rstride=10, cstride=10)
# plots out data
plt.show()
print(axes3d.__file__)
# better wire frame
def grid():
t = arange(0.0, 100.0, 0.1)
s = sin(0.1*pi*t)*exp(-t*0.01)
# test plot
ax = subplot(111)
plot(t,s)
# sets xaxis gridlines
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
ax.xaxis.set_minor_locator(MultipleLocator(5))
# yaxis gridlines
ax.yaxis.set_major_locator(MultipleLocator(0.5))
ax.yaxis.set_minor_locator(MultipleLocator(0.1))
ax.xaxis.grid(True,'minor')
ax.yaxis.grid(True,'minor')
# these well be the big main gridlines they'll be bigger
ax.xaxis.grid(True,'major',linewidth=2)
ax.yaxis.grid(True,'major',linewidth=2)
# customizing the grid. not the subplot2grid grid, the lines on the graph gird
# Calls function
ThreeD() |
838316fe1982df74260026165555da37548bb9c5 | hyperlolo/Leetcode | /Easy/twoSumEasy/twosum.py | 1,208 | 3.953125 | 4 | # Difficulty: Easy
# Given an array of integers numbers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
# Return the indices of the two numbers (1-indexed) as an integer array answer of size 2, where 1 <= answer[0] < answer[1] <= numbers.length.
# You may assume that each input would have exactly one solution and you may not use the same element twice.
# Example 1:
# Input: numbers = [2,7,11,15], target = 9
# Output: [1,2]
# Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
# Example 2:
# Input: numbers = [2,3,4], target = 6
# Output: [1,3]
# Example 3:
# Input: numbers = [-1,0], target = -1
# Output: [1,2]
# Constraints:
# 2 <= numbers.length <= 3 * 104
# -1000 <= numbers[i] <= 1000
# numbers is sorted in increasing order.
# -1000 <= target <= 1000
# Only one valid answer exists.
# Solution:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict = {}
for i, a in enumerate(nums):
rem = target - a
if rem in dict:
return[dict[rem], i]
dict[a] = i
return[]
|
67df4df9c107678587d85c29904eecde9e0e3455 | shonihei/road-to-mastery | /algorithms/linked-list-algorithms/get_Nth.py | 626 | 3.84375 | 4 | class Node:
def __init__(self, v=None, n=None):
self.key = v
self.next = n
# iteratively get the nth element
def get_Nth(node, n):
while n != 0:
if not node.next:
raise IndexError("n is larger than the length of the list")
node = node.next
n -= 1
return node.key
def get_Nth_rec(node, n):
if not node:
raise IndexError("n is larger than the length of the list")
if n == 0:
return node.key
else:
return get_Nth_rec(node.next, n-1)
a = Node("a", Node("b", Node("c", Node("d"))))
print(get_Nth(a, 2))
print(get_Nth_rec(a, 2))
|
206a95b02a6d6ebff98aebb4dc20b4cc6588a359 | vdesire2641/python-for-programming | /pyc13.py | 164 | 3.765625 | 4 | # use of ifelse selection statements
a = 5
b = 3
if a>b:
c = 10
else:
c = 20
print(c)
# use of simple if selection statement
if b>a:
c = 25
print(c)
|
4adfa8889f2ff487e4187952106c99415cd9ca25 | Boissineau/challenge-problems | /leetcode/Easy/ReverseLinkedList/reverse.py | 789 | 3.75 | 4 | class Solution:
def reverseList(self, head):
curr = head
previous = None
while True:
if curr is None:
break
tmp_curr = curr.next
curr.next = previous
previous = curr
if tmp_curr is None:
break
curr = tmp_curr
return curr
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
if __name__ == '__main__':
node = ListNode(0);
head = node
for i in range(1,10):
node.next = ListNode(i)
node = node.next
x = Solution()
v = x.reverseList(head)
for i in range(10):
print(v.val)
v = v.next
|
f9f0dfc40b556069c3a6f18dc569b08c4c4b8b57 | MishRanu/udemy-python-masterclass | /hello.py | 254 | 3.875 | 4 | print("Hello world!")
hello="hello"
# anurag=input("Please enter your name")
print(hello+ " " )
print('The pet shop owner said "No, no, \'e\'s eh.... he\s resting\"')
print("h" in "hello")
test="He's probably pining"
print(test[0::3])
print(test[1:9:2])
|
1e7af9b8b42474af1e5d79adb12cab6c7d17dd70 | johanaluna/Sorting | /src/iterative_sorting/iterative_sorting.py | 2,628 | 3.953125 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort( arr ):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
for n in range(smallest_index+1, len(arr) ):
# If the value at n is smaller than the value
# at smallest_index, swap them
if arr[n] < arr[smallest_index]:
pivot = arr[smallest_index]
arr[smallest_index] = arr[n]
arr[n] = pivot
return arr
# TO-DO: implement the Bubble Sort function below
def bubble_sort( arr ):
count = 0
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
second_index = i + 1
# if the number right in smaller that the smallest_index:
if arr[second_index] < arr[smallest_index]:
pivot = arr[smallest_index]
arr[smallest_index] = arr[second_index]
arr[second_index] = pivot
count += 1
#check that it has been not changes or swaps
if count > 0:
selection_sort(arr)
return arr
# STRETCH: implement the Count Sort function below
# Video: https://www.youtube.com/redirect?v=7zuGmKfUt7s&event=video_description&q=http%3A%2F%2Fwww.geeksforgeeks.org%2Fcounting-sort%2F&redir_token=IEcQm-hylFwxrPj5izBbWl1NHTB8MTU4MjE0MzQwOEAxNTgyMDU3MDA4
def count_sort( arr, maximum=-1 ):
# counting number of eleements having distinct keys
# doing dome arithmetic to calculate the positions
# of each element in the output ()
max = arr[0]
# check what is the maximun value in the array
for x in arr:
if x > max:
max = x
# create a counter with the same size than
# the maximun number of the input
counter = [0] * (max+1)
# counter = [0 for i in range(max+1)]
# create the output array that it's going to
# content the sln
output = [0] * len(arr)
# output = [0 for _ in arr]
indexes = range (1,max+1)
# count each element in arr and place the count
# at the appropiate index in the counter array
for n in arr:
counter[n]+= 1
# modify the counter array by adding
# the previous counts
for i in indexes:
counter[i] +=counter[i-1]
# for each element in the initial array find this
# index in counter and substract 1. The value
# in counter is used as index in the output array
# and we save there the value from the inital array
for x in arr:
output[counter[x]-1]=x
counter[x]-=1
return output
|
e6edf4cfab3566d73c470968b21a6a87ba724fe8 | Phlosioneer/zork-rs | /tools/verb_parser.py | 397 | 3.890625 | 4 |
def parse_number(num):
low_bits = num & 0xFF
high_bits = num >> 8
print("low bits: " + str(low_bits))
for bit in range(0, 8):
mask = 1 << bit
value = mask & high_bits
if value:
print("Bit " + str(bit + 8) + " is true.")
print("All other bits are false.")
while True:
num = int(input("Encoded number: "))
parse_number(num)
|
9126a5391d090b58187173c147286d367445910c | daniel-reich/ubiquitous-fiesta | /MhtcQNMbkP82ZKJpm_17.py | 275 | 3.5 | 4 |
from collections import Counter
def get_notes_distribution(students):
print(students)
students_list_of_lists = [s['notes'] for s in students]
res = dict(Counter([item for sublist in students_list_of_lists\
for item in sublist if item in [1,2,3,4,5]]))
return res
|
f969d62d5e0e8e9255c3b44895e8174afae53f42 | gabriellaec/desoft-analise-exercicios | /backup/user_212/ch150_2020_04_13_20_03_38_368317.py | 151 | 3.703125 | 4 | def calcula_pi (n):
p=0
total=0
for i in range (n):
p+=(6/n**2)
total=(p)**(1/2)
return total
|
6d49a4fd133303c1585d2cd11e3464d0545ab889 | MuberraKocak/data-structure-python | /TwoPointer/remove_duplicates.py | 380 | 3.78125 | 4 | def remove_duplicates(arr):
next_non_duplicate = 1
i = 1
while(i< len(arr)):
if arr[next_non_duplicate - 1] != arr[i]:
arr[next_non_duplicate] = arr[i]
next_non_duplicate += 1
i += 1
return next_non_duplicate
arr = [2, 3, 3, 3, 6, 9, 9]
print(remove_duplicates(arr))
# Time complexity is O(N)
# Space complexity is O(1)
|
c4651cd8e54a6a86fa64144ee5594b97769ceaf5 | mba-mba/HacktoberFest2020-1 | /Python/heterogram.py | 225 | 3.875 | 4 | string=input()
lst=[]
for i in string.lower():
if ord(i)>=ord('a') and ord(i)<=ord('z'):
lst.append(i)
s1=set(lst)
if len(s1)==len(lst):
print("Heterogram string")
else:
print("its not heterogram string")
|
299cb41058a74756f6508bec62953c203532fdf4 | KIMJOOYEON97/pythonStudy | /20.05 studyData/์์ง๋ ๋ชปํผ ๋ฌธ์ ์์.py | 5,551 | 3.78125 | 4 | '''
i=0
while i<5:
print("{}๋ฒ ์ข
์๋ฌธ์ฅ ์คํ".format(i))
i +=1
else:
print("์กฐ๊ฑด์์ด ๊ฑฐ์ง์ธ ๊ฒฝ์ฐ์ ์คํ ๋ฌธ์ฅ") #๋ฐ๋ณต๊ตฌ๋ฌธ ๋ค ์คํํ๋ค์์ ํ๋ฒ์คํ. ๋ง์ฝ ๊ฑฐ์ง์ธ ๊ฒฝ์ฐ ์ด๊ฒ๋ง ์คํ)
print("๋ฉ์ธ ํ๋ก๊ทธ๋จ ์คํ ์ฝ๋")
'''
'''
# ๋ฌธ์ 6] ๋ค์๊ณผ ๊ฐ์ ๋ชจํ์ผ๋ก ์ถ๋ ฅ๋๊ฒ ํ์ธ์. (๋จ, ํ์ด์ฌ ์์์ ์ฌ์ฉ์ํจ. ) ์์๋ฌธ์์ฌ์ฉX
6-1 6-2 6-3 6-4
* ***** * *****
** **** ** ****
*** *** *** ***
**** ** **** **
***** * ***** *
'''
'''
for i in range(5):
for y in range(i+1):
print("*",end='')
print()
print()
#or
i=0
while i<5:
x=0
j=i+1
while x <j:
x +=1
print("*",end='')
print()
i +=1
print()
#2
for i in range(5):
for y in range(5-i):
print("*",end='')
print()
print()
#or
i=0
while i<5:
x=0
y=5-i
i +=1
while x <y:
print("*",end='')
x +=1
print()
print()
#3
for i in range(5):
for j in range(4-i):
print(" ",end="")
for j in range(i+1):
print(end="*")
print()
print()
i=0
while i<5:
x=0 #๋ค์ x๋ 0
y=4-i #๊ณต๋ฐฑ
if x<=y: #ํญ์ x=0! ์ด๊ฑด ๋ฐ๋์ x<=y์ด์ด์ผ ํจ. y๊ฐ 0์ผ ๊ฒฝ์ฐ์๋ ์ถ๋ ฅ์ด ๋์ผํจ
print(" "*y,end="") #y๋ ๊ณต๋ฐฑ
x=i+1 # ๊ทธ๋์ ์ ํด์ง ํ์๋ ๋๋ง๋ค x์ i+1 ์ฌํ ๋น
print("*"*x)
i += 1
print()
#4
for i in range(5):
for j in range(i):
print(" ",end="")
for j in range(5-i):
print(end="*")
print()
i=0
while i<5: # i 0 1 2 3 4
x=0
y=5-i
if x<y: # x๊ฐ ํญ์ 0
print(" "*i,end="") #๋น์นธ์ 0 1 2 3 4 ์ด์ด์ผํ๋๊น i๋ฅผ ์ฐ๋ฉด ๋
print("*"*y) #y๊ฐ 5,4,3,2,1์ด ๋ ์ ์๊ฒ #y๋ ๋ณ
i+=1
print()
count=0
for x in range(2,101):
flag = True #True์ด๋ฉด ์์
#์์ ํ๋ณ...
for y in range(2,x):
if x%y==0:
flag=False
break
#(break) break๋ฅผ ๋ฃ์ง์์๋ ์๋์ด ๋๋ ์ด์ ๋???
if flag:
print(x,end=" ") #์์์ถ๋ ฅ
count += 1
print()
print(count,"๊ฐ์ ์์๊ฐ ์กด์ฌํจ!!")
'''
'''
6-5 ์ถ๋ ฅ ์ค์๋ฅผ ์
๋ ฅํ๋ฉด ๋ค์๊ณผ ๊ฐ์ด ์ถ๋ ฅ
์
๋ ฅ ์ค์ ํ์์ด์ฌ์ผ๋ง ํจ.
hint:๋ณ,๊ณต๋ฐฑ,์ค์,๋ฐ๋ณต๋ฌธ์ ์ํ ๋ณ์,flag(booL): ๋ฐ์ ์ ์ค ์ ์๋ ์ ํธ
ํ์ ์ค์๋ฅผ ์
๋ ฅ: 7
* st: ์ค์ด ๋ฐ๋๋๋ง๋ค +2(์ค์์ ๋ฐ)/๋ฐ ๋์ผ๋ฉด, -2
*** sp: ์ค์๋ฅผ //2(์ด๊ธฐ๊ฐ), ์ค์์ ๋ฐ ์ -1,ํ +1
*****
*******
*****
***
*
'''
'''
x=y=0; num=1
while num: #num=1 True
ln=int(input("ํ์ ์ค์๋ฅผ ์
๋ ฅ: "))
flag=True;et=ln//2;star=1
for x in range(ln):
for y in range(et):print(" ",end='') #et=3=>๊ณต๋ฐฑ์ 3๋ฒ ์ถ๋ ฅ et=2 et=1 x=3 => et=0 //et=1...
for y in range(star):print("*",end='') #star=1=>๋ณ 1๋ฒ ์ถ๋ ฅ st=3 st=5 x=3 => st=7 //st=5...
print() #๊ฐํ
if x ==(ln//2): flag=False # x= 0,1,2,3,4,5,6// x==3 flag=False๋ก ๋ฉ์ถค=>else๋ก ๋์ด๊ฐ.
if flag: et-=1; star+=2 # x๊ฐ 3์ดํ์ ์ x=0,1,2,3 ******* => ์ธ์ ๋ ์๋ํ๋ฉด ์ถ๋ ฅ์ด ์์ ์์
else: et+=1;star-=2 # x๊ฐ 3๋ณด๋ค ํฐ ์ x=4,5,6 *****
num = int(input("๊ณ์ํ๊ฒ ์ต๋๊น?[0.์ข
๋ฃ, 1.๊ณ์]"))
import os # os๋ ํ์ด์ฌ์์ ์ ๊ณตํ๋ ๊ธฐ๋ณธ ๋ผ์ด๋ธ๋ฌ๋ฆฌ
# os์ ๊ด๋ จ๋ ํจ์๋ค์ด ์ ์ฅ๋ ๋ชจ๋
# system() => os์ ์์คํ
๋ช
๋ น์ด๋ฅผ ์ฌ์ฉํ๊ฒํจ
i,j=0,0 ;num=1
while num:
os.system("cls") #"cls"๋ ์์ ์๋ ๊ฒ ๋ ๋ ค์ค
ln= int(input("ํ์ ์ค์๋ฅผ ์
๋ ฅ :"))
sp=ln//2;st=1;flag=True #flag=๋ฐ์ ์ ์ํ ๊ฐ
for i in range(ln):
for j in range(sp):print(end=" ") #๊ณต๋ฐฑ
for j in range(st):print(end="*") #๋ณ
print() #์ค๋ฐ๊ฟ
if i == (ln//2): flag=False
if flag: sp-=1; st+=2
else: sp+=1;st-=2
num = int(input("๊ณ์ํ๊ฒ ์ต๋๊น?[0.์ข
๋ฃ,1.๊ณ์] : "))
# ๋ฌธ์ 3] 1~15๊น์ง ๋๋ค ๊ฐ์ ์ค๋ณต ์์ด 3๊ฐ ์์ฑํ์ฌ ์ถ๋ ฅํ๋ ์ฝ๋ ์์ฑ
from random import random
a,b,c=0,0,0
while True:
su=int(random()*15)+1
a=su #su=a ํ๋ฉด 0์ด ๋์จ๋ค. ์๋ํ๋ฉด ์ค๋ฅธ์ชฝ์ ์๋๊ฒ ์ผ์ชฝ์ ํ ๋น๋๊ธฐ ๋๋ฌธ
break
while True:
su=int(random()*15)+1
if su !=a:
b=su
break
while True:
su=int(random()*15)+1
if su != a and su !=b:
c=su
break
print(a, b, c)
from random import random
num1,num2,num3=0,0,0
while True:
su = int(random()*15)+1
if num1 != su:
num1=su
break
while True:
su = int(random()*15)+1
if num1 != su and num2 !=su:
num2 = su
break
while True:
su = int(random()*15)+1
if num1 != su and num2 != su and num3 !=su:
num3 =su
break
print("{} {} {}".format(num1,num2,num3))
'''
#์๋ ์ฐ์ด๋ด๋ผ, ๋ณ๋ ์ฐ์ด๋ด๋ผ
ln=int(input("ํ์ ์ค ์๋ฅผ ์
๋ ฅํ์ธ์: "))
snt=0;st=1;et=(ln//2);flag=True
#x,y,j=0,0,0
for x in range(ln):
for y in range(et): print("-",end="")
print("*",end="")
for j in range(snt): print("-",end="")
print("*",end="")
for y in range(et): print("-",end="")
print()
if x%(ln//2)==0: flag=False
if flag:
et -= 1
snt +=2
else:
et +=1
snt -=2
|
f1ebe6f60c2e2d3e6ef7dd0ab8492b6023d852eb | dedekinds/pyleetcode | /680_Valid Palindrome II_easy.py | 592 | 3.53125 | 4 |
'''
680. Valid Palindrome II
2017.12.23
'''
ๅฆๆๅ็ฐไธๅฐๅๆ๏ผ้ฃไน็ปไธๆฌกๆบไผๆ้ฃไธชๅญ็ฌฆๅ้ค
class Solution:
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
ispalindrome=lambda s:s==s[::-1]
conbination=lambda x,s: s[:x]+s[x+1:]
left=0
right=len(s)-1
while left<right:
if s[left]!=s[right]:
return ispalindrome(conbination(left,s)) or ispalindrome(conbination(right,s))
left+=1
right-=1
return True |
1b786b004eb3df0ac77b0afa4f35bdc38dd2a343 | sergiodealencar/courses | /material/curso_em_video/ex071.py | 1,393 | 3.75 | 4 | # print('=='*15)
# print('{:^30}'.format('BANCO PATINHAS'))
# print('=='*15)
# nota50 = nota20 = nota10 = nota1 = 0
# valor = int(input('Que valor vocรช quer sacar? R$'))
# while valor != 0:
# while valor >= 50:
# valor -= 50
# nota50 += 1
# while valor >= 20:
# valor -= 20
# nota20 += 1
# while valor >= 10:
# valor -= 10
# nota10 += 1
# while valor >= 1:
# valor -= 1
# nota1 += 1
# if nota50:
# print(f'Total de {nota50} cรฉdula(s) de R$50.')
# if nota20:
# print(f'Total de {nota20} cรฉdula(s) de R$20.')
# if nota10:
# print(f'Total de {nota10} cรฉdula(s) de R$10.')
# if nota1:
# print(f'Total de {nota1} cรฉdula(s) de R$1.')
# print('=='*15)
# print('Volte sempre ao BANCO PATINHAS! Tenha um bom dia!')
print('=='*15)
print('{:^30}'.format('BANCO PATINHAS'))
print('=='*15)
valor = int(input('Que valor vocรช quer sacar? R$'))
total = valor
ced = 50
totced = 0
while True:
if total >= ced:
total -= ced
totced += 1
else:
if totced > 0:
print(f'Total de {totced} cรฉdulas de R${ced}')
if ced == 50:
ced = 20
elif ced == 20:
ced = 10
elif ced == 10:
ced = 1
totced = 0
if total == 0:
break
print('=' * 30)
print('Volte sempre ao BANCO PATINHAS! Tenha um bom dia!')
|
8bd72b0fb013d9fcaf699fea168251e32562a851 | hanskiebach/metrobus | /[hanskiebach]/[metrobus]/week2/homework.py | 240 | 3.5 | 4 | import logging
logging.basicConfig(level=logging.DEBUG)
def squared_threes():
return_value = [value ** 2 for value in range(3,100, 3)]
return return_value
if __name__ == "__main__":
for x in squared_threes():
print(x) |
6ec33929bdce0f29f2d7e61918e8828f7c648ee9 | leoren6631/Learning-Python | /quadratic_solve.py | 295 | 3.75 | 4 | import math
def quadratic(a, b, c):
if a != 0:
x1 = (-b + math.sqrt(b*b - 4*a*c)) / (2*a)
x2 = (-b - math.sqrt(b*b - 4*a*c)) / (2*a)
return (x1, x2)
else:
return('wrong input')
print(quadratic(2, 3, 1))
print(quadratic(1, 3, -4))
print(quadratic(0,2,3)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.