text stringlengths 37 1.41M |
|---|
def falsi(x0, x1):
x2 = x0 - ((x1-x0)/(f(x1)-f(x0))*f(x0))
return x2
def f(x):
result = x*x - 2*x - 8
return result
#x0 = eval(input("input x0: "))
#x1 = eval(input("input x1: "))
#print(falsi(x0, x1))
|
def is_password_strong(password):
symbols = ["!","@","#","$","%","^","&","*","(",")",'_','-','=','+','|','\\','/','?','.','>',',','<',';',':']
letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u''v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
number = ['0','1','2','3','4','5','6','7','8','9']
hasnumber = False
hassymbol = False
islongenough = False
hasletter = False
if (len(password)>=8):
for i in range(len(symbols)):
if (symbols[i] in password):
hassymbol = True
break
else:
hassymbol = False
for i in range(len(letters)):
if (letters[i] in password):
hasletter = True
break
else:
hasletter = False
for i in range(len(number)):
if (number[i] in password):
hasnumber = True
break
else:
hasnumber = False
islongenough = True
else:
islongenough = False
return hasletter and hasnumber and hassymbol and islongenough
|
"""Planet.py:
To draw a picture to imitate how planets
run around the sun using turtle.
__author__="Liyuhao"
__pkuid__="1800011761"
__email__="1800011761@pku.edu.cn"
"""
import turtle
import math
m = turtle.Screen()
sun = turtle.Turtle()
sun.hideturtle()
sun.up()
sun.goto(100, 0)
sun.dot(50, "red")
alexa = turtle.Turtle()
alexa.color("red")
alexa.shape("circle")
alexb = turtle.Turtle()
alexb.color("green")
alexb.shape("circle")
alexc = turtle.Turtle()
alexc.color("blue")
alexc.shape("circle")
alexd = turtle.Turtle()
alexd.color("yellow")
alexd.shape("circle")
alexe = turtle.Turtle()
alexe.color("orange")
alexe.shape("circle")
alexf = turtle.Turtle()
alexf.color("purple")
alexf.shape("circle")
alexg = turtle.Turtle()
alexg.color("gray")
alexg.shape("circle")
alexh = turtle.Turtle()
alexh.color("brown")
alexh.shape("circle")
alexa.up()
alexa.goto(20000 ** 0.5, 0)
alexa.down()
alexb.up()
alexb.goto(30000 ** 0.5, 0)
alexb.down()
alexc.up()
alexc.goto(40000 ** 0.5, 0)
alexc.down()
alexd.up()
alexd.goto(50000 ** 0.5, 0)
alexd.down()
alexe.up()
alexe.goto(60000 ** 0.5, 0)
alexe.down()
alexf.up()
alexf.goto(70000 ** 0.5, 0)
alexf.down()
alexg.up()
alexg.goto(80000 ** 0.5, 0)
alexg.down()
alexh.up()
alexh.goto(90000 ** 0.5, 0)
alexh.down()
for i in range(1000000):
alexa.speed(0)
alexa.goto(20000 ** 0.5 * math.cos(math.pi/90 * i),
10000 ** 0.5 * math.sin(math.pi/90 * i))
alexb.speed(0)
alexb.goto(30000 ** 0.5 * math.cos(math.pi/110 * i),
20000 ** 0.5 * math.sin(math.pi/110 * i))
alexc.speed(0)
alexc.goto(40000 ** 0.5 * math.cos(math.pi/130 * i),
30000 ** 0.5 * math.sin(math.pi/130 * i))
alexd.speed(0)
alexd.goto(50000 ** 0.5 * math.cos(math.pi/150 * i),
40000 ** 0.5 * math.sin(math.pi/150 * i))
alexe.speed(0)
alexe.goto(60000 ** 0.5 * math.cos(math.pi/170*i),
50000 ** 0.5*math.sin(math.pi/170 * i))
alexf.speed(0)
alexf.goto(70000**0.5*math.cos(math.pi/190*i),
60000**0.5*math.sin(math.pi/190*i))
alexg.speed(0)
alexg.goto(80000**0.5*math.cos(math.pi/210*i),
70000**0.5*math.sin(math.pi/210*i))
alexh.speed(0)
alexh.goto(90000**0.5*math.cos(math.pi/230*i),
80000**0.5*math.sin(math.pi/230*i))
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if head is None:
return False
fast = head.next
while fast:
if fast == head:
return True
fast = fast.next.next if fast.next else None
head = head.next
return False
|
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: n
@return: The new head of reversed linked list.
"""
def reverse(self, head):
prev = None
while head :
temp, head.next = head.next, prev
prev, head = head, temp
return prev
# 总耗时 1007 ms
# 您的提交打败了 63.75% 的提交! |
#!/usr/bin/env python3
class Solution:
"""
@param: source: source string to be scanned.
@param: target: target string containing the sequence of characters to match
@return: a index to the first occurrence of target in source, or -1 if target is not part of source.
"""
def strStr(self, source, target):
if source == None or target == None : return -1
if target == '' : return 0
if source == '' : return -1
source_len = len(source)
target_len = len(target)
print(source[0 : 0 + target_len])
for i in range(0, source_len - target_len + 1) :
if target == source[i : i + target_len] :
return i
return -1
# 总耗时 821 ms
# 您的提交打败了 99.80% 的提交! |
#fibonacci series
import sys
n=int(input())
list = [0,1]
for i in range(2,n):
list.append(list[i-1]+list[i-2])
print(list)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
filename = input("File: ")
def openFile(fn):
f = open(fn,'r',encoding="utf8")
d = f.read()
f.close()
return d
def saveFile(fn,d):
f = open(fn,'w',encoding="utf8")
f.write(d)
f.close()
content = openFile(filename)
content = content.replace(" ", " ").replace("\r ", "\r").replace(" \r", "\r").replace("“","\"").replace("”","\"").replace("‘","'").replace("’","'").strip()
saveFile(filename, content) |
import math # импротируем модуль math
x = 3.265
# целое число, ближайшее целое снизу, ближайшее целое сверху
print(math.trunc(x), math.floor(x), math.ceil(x))
print(math.pi) # константа пи
print(math.e) # число Эйлера
y = math.sin(math.pi / 4) # math.sin – синус
print(round(y, 2))
y = 1 / math.sqrt(2) # math.sqrt – квадратный корень
print(round(y, 2))
#####################################
# логические операции
print('and:')
print(False and False) = FALSE
print(False and True) = FALSE
print(True and False) = FALSE
print(True and True) = TRUE
print()
print('or:')
print(False or False) = FALSE
print(False or True) = TRUE
print(True or False) = TRUE
print(True or True) = TRUE
print()
print('not:')
print(not False) = TRUE
print(not True) = FALSE
print()
# логические выражения
a = True
b = False
c = True
f = a and not b or c or (a and (b or c))
print(f)
#####################################
a = 2
b = 5
print(a < b) # меньше
print(b > 3) # больше
print(a <= 2) # меньше или равно
print(b >= 7) # больше или равно
print(a < 3 < b) # двойное сравнение
print(a == b) # равенство
print(a != b) # неравенство
print(a is b) # идентичность объектов в памяти
print(a is not b) # a и b – разные объекты (хотя значения их могуть быть равны)
x = int(input('Enter the card: ')) #37000
r = int(x / 1000)
(r >= 37 and r <= 42) or (r >= 5500 and r <6000)
print() |
import numpy as py
import pandas as pd
import matplotlib.pyplot as plt
#reading the file
datasets = pd.read_csv('Salary.csv')
#dividing dataset into x and y
X=datasets.iloc[:,:-1].values
Y=datasets.iloc[:,1].values
print(X)
print(Y)
#splitiing dataset into test and train
from sklearn.cross_validation import train_test_split
X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=1/3,random_state=0)
print('independent train')
print(X_train)
print('dependent train')
print(Y_train)
print('independent test')
print(X_test)
print('dependent test')
print(Y_test)
#implement our classifier
from sklearn.linear_model import LinearRegression
linreg=LinearRegression()
linreg.fit(X_train,Y_train)
y_predict=linreg.predict(X_test)
d={'org':Y_test,'pre':y_predict}
df=pd.DataFrame(data=d)
print(df)
#Implement the graphs
plt.scatter(X_train,Y_train)
plt.plot(X_train,linreg.predict(X_train),color='red')
plt.show()
linreg.fit(X_test,Y_test)
plt.scatter(X_test,Y_test,color='red')
plt.plot(X_test,linreg.predict(X_test))
plt.show() |
# get user email address
email= input("Enter your email address: ").strip()
#slice out user name
username= email[0:email.index('@')]
#slice out domain name
#garimagr@gmail.com
ind=email.index('@')+1
domainname= email[ind:]
#format message
message= "The user name is {} and the domain name is {}"
output=message.format(username,domainname)
#print on screen
print(output)
|
"""
Created on Thu Jun 24 12:44:36 2021
@author: Yousif Alyousif
"""
import tkinter as tk
import sqlite3
from tkinter import ttk
#con = sqlite3.connect('FinanceManager.db')
#cur = con.cursor()
#cur.execute("""CREATE TABLE finances (
# item blob,
# expense blob,
# qty blob,
# sign blob,
# date blob
# )""")
# save function + clear entry boxes
def record():
con = sqlite3.connect('FinanceManager.db')
cur = con.cursor()
cur.execute("INSERT INTO finances VALUES (:item_v, :expense_v, :qty_v, :sign_v, :date_v)",
{
'item_v': item_entry.get(),
'expense_v': expense_entry.get(),
'qty_v': qty_entry.get(),
'sign_v': sign_entry.get(),
'date_v': date_entry.get()
})
con.commit()
con.close()
item_entry.delete(0, 50)
expense_entry.delete(0, 50)
qty_entry.delete(0, 50)
sign_entry.delete(0, 50)
date_entry.delete(0, 50)
# display function
def display():
con = sqlite3.connect('FinanceManager.db')
cur = con.cursor()
cur.execute("SELECT * FROM finances")
financial_records = cur.fetchall()
for record in financial_records:
print(record)
tree.insert("", tk.END, values=record)
con.commit()
con.close()
# remove function
def remove():
con = sqlite3.connect('FinanceManager.db')
cur = con.cursor()
cur.execute("DELETE from finances WHERE oid = " + delete_entry.get())
delete_entry.delete(0, 50)
con.commit()
con.close()
# gui
window = tk.Tk()
item_entry = tk.Entry(window, width=20)
item_entry.grid(row=1, column=0, padx=20)
expense_entry = tk.Entry(window, width = 20)
expense_entry.grid(row=1, column=1, padx=20)
qty_entry = tk.Entry(window, width=10)
qty_entry.grid(row=1, column=2, padx=20)
sign_entry = tk.Entry(window, width=10)
sign_entry.grid(row=1, column=3, padx=20)
date_entry = tk.Entry(window, width=10)
date_entry.grid(row=1, column=4, padx=20)
delete_entry = tk.Entry(window, width=10)
delete_entry.grid(row=1, column=6, padx=20)
item_label = tk.Label(window, text='Item')
item_label.grid(row=0, column=0, padx=20)
expense_label = tk.Label(window, text='Expense')
expense_label.grid(row=0, column=1, padx=20)
qty_label = tk.Label(window, text='Qty')
qty_label.grid(row=0, column=2, padx=20)
sign_label = tk.Label(window, text='Signed By')
sign_label.grid(row=0, column=3, padx=20)
date_label = tk.Label(window, text='Date')
date_label.grid(row=0, column=4, padx=20)
save_button = tk.Button(window, text='Save', command=record)
save_button.grid(row=0, column=5, padx=20)
delete_button = tk.Button(window, text='Remove Record', command=remove)
delete_button.grid(row=0, column=6, padx=20)
tree = ttk.Treeview(window, column=("c1", "c2", "c3", "c4", "c5"), show='headings')
tree.grid(columnspan=5)
tree.column("#1", anchor=tk.CENTER)
tree.heading("#1", text="Item")
tree.column("#2", anchor=tk.CENTER)
tree.heading("#2", text="Expense")
tree.column("#3", anchor=tk.CENTER)
tree.heading("#3", text="Qty")
tree.column("#4", anchor=tk.CENTER)
tree.heading("#4", text="Signed")
tree.column("#5", anchor=tk.CENTER)
tree.heading("#5", text="Date")
display_button = tk.Button(window, text='Display Expense Records', command=display)
display_button.grid(row=1, column=5, padx=20)
window.mainloop() |
def writeBackward1(string):
if string == "":
return string
else:
return string[len(string)-1]+writeBackward(string[0:len(string)-1])
def writeBackward2(s):
if s== "":
return s
else:
return writeBackward2(s[1:]) + s[0]
s = raw_input()
print writeBackward2(s)
|
import random
import math
# initialize global variables used in your code here
num_range = 100
num_guesses = int(math.ceil(math.log(num_range,2)))
secret_number = random.randint(0, 100)
# helper function to start and restart the game
def new_game():
print "New game. Range is from 0 to",num_range
print "Number of remaining guesses is",num_guesses
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
global num_range, num_guesses, secret_number
num_range = 100
num_guesses = int(math.ceil(math.log(num_range,2)))
secret_number = random.randint(0, 100)
print
new_game()
def range1000():
# button that changes the range to [0,1000) and starts a new game
global num_range, num_guesses, secret_number
num_range = 1000
num_guesses = int(math.ceil(math.log(num_range,2)))
secret_number = random.randint(0, 1000)
print
new_game()
def input_guess(guess):
# main game logic goes here
global num_range, num_guesses,secret_number
print
print "Guess was ", guess
num_guesses = num_guesses - 1
print "Number of remaining guesses is",num_guesses
if int(guess) > secret_number:
print "Lower!"
elif int(guess) < secret_number:
print "Higher!"
else :
print "Correct!"
print
if num_range == 100:
range100()
else:
range1000()
if num_guesses == 0:
print "You lose"
print
if num_range == 100:
range100()
else:
range1000()
# call new_game
new_game()
# always remember to check your completed program against the grading rubric |
high = 100 #high end of guess - cut as needed
low = 0 # low end of guess - cut as needed
numGuesses = 0
print 'Please think of a number between 0 and 100!'
while True:
guess = (high + low)/2
print "Is your secret number " + str(guess) + "?"
user = raw_input ("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")
if user == 'h':
high = guess
numGuesses +=1
elif user == 'l':
low = guess
numGuesses +=1
elif user == 'c':
numGuesses +=1
break
else:
print "Sorry, I did not understand your input."
print "Game over. Your secret number was: " + str(guess)
#print "I got it in " + str(numGuesses) + " guesses!" |
from math import ceil, sqrt
import numpy as NP
# Get the prime divisors of a number.
# This function come from http://codereview.stackexchange.com/questions/19509/functional-prime-factor-generator
def factor(n):
if n <= 1: return []
prime = next((x for x in range(2, ceil(sqrt(n))+1) if n%x == 0), n)
result = [prime] + factor(n//prime)
# This algorithm return duplicated values. Let's return an array of unique values
result = list(set(result))
return result
# Set the list of integer to process
integers = [15, 21, 24, 30, 49]
# Store pairs
pairs = []
# Map function creating every pairs
def map(n):
factors = factor(n)
map_keys = []
for num in factors:
map_keys.append((num, n))
return map_keys
# Reduce function summing the values of every keys
def reduce(pairs):
result = dict()
last_key = None
for pair in pairs:
key = pair[0]
if key == last_key:
result[key] += pair[1]
else:
result[key] = pair[1]
last_key = key
return result
# Create pairs by calling map function for every integers
for integer in integers:
tuples = map(integer)
for single_tuple in tuples:
pairs.append(single_tuple)
# Sort pairs by key
pairs = sorted(pairs, key=lambda key: key[0])
|
# -*- coding: utf-8 -*-
#Author: Aristotle Ducay
#Date: 09/16/2020
#File: Cars.py
#List objects for car makes, models and years
years = [2001, 1989, 2019, 1999]
makes = ["Honda", "Toyota", "Mercedes", "Nissan"]
models = ["Accord", "Camry", "C63AMG", "Skyline"]
#indexing values for years and makes list
years[2] = 2019
makes[3] = "Nissan GTR"
#adding to the 3 list objects with var.append()
makes.append("BMW")
models.append("M6")
years.append("2009")
print("Car1: ", years[0], "", makes[0], "", models[0])
print("Car2: ", years[1], "", makes[1], "", models[1])
print("Car3: ", years[2], "", makes[2], "", models[2])
print("Car4: ", years[3], "", makes[3], "", models[3])
print("Car5: ", years[4], "", makes[4], "", models[4])
|
#!/usr/bin/env python
def load_dict(dict_path):
""" Read a dictionary located at the path provided. Add each of the words
in the dictionary to a set that can then be used to provide spelling
suggestions.
Returns a dict with all words in the dictionary.
"""
words = {}
# add each line to our set representing the dictionary
for line in dict_path:
stripped = str.strip(line)
lower_case = stripped.lower()
words[lower_case] = stripped
return words
|
from abc import ABC, abstractmethod
class A(ABC):
@abstractmethod
def show(self):
pass
class B(A):
def show(self):
print('show method')
b1 = B()
b1.show() |
"""
Creational:
- Factory Method:
3 Component => 1.Creator, 2.Product, 3.Client
"""
# Factory Method allows us to create a super_class that is responsible \
# for creating an object and allow the sub_class to be able to change the \
# type of object being made
from abc import ABC, abstractmethod
# -------------------------------- Creator
class Creator(ABC):
@abstractmethod
def make(self):
pass
def call_edit(self):
product = self.make()
result = product.edit()
return result
class JsonCreator(Creator):
def make(self):
return Json() # Return Products
class XmlCreator(Creator):
def make(self):
return Xml() # Return Products
# ---------------------------------
# --------------------------------- Product
class Product(ABC):
@abstractmethod
def edit(self):
pass
class Json(Product):
def edit(self):
return 'Editing Json file'
class Xml(Product):
def edit(self):
return 'Editing Xml file'
# --------------------------------
# -------------------------------- Client
def client(format):
return format.call_edit()
# --------------------------------
print(client(JsonCreator()))
# ================================================== simple sample ==================================================
class A:
def __init__(self, name, format):
self.name = name
self.format = format
class B:
def edit(self, file): # Client
edit = self._get_edit(file)
return edit(file)
def _get_edit(self, file): # Creator
if file.format == 'json': # Identifier
return self.json_edit
elif file.format == 'xml': # Identifier
return self.xml_edit
else:
raise ValueError('This type of file is not supported')
def json_edit(self, file): # Product
print(f'Editing Json file... {file.name}')
def xml_edit(self, file): # Product
print(f'Editing Xml file... {file.name}')
a1 = A('first', 'xml')
b1 = B()
b1.edit(a1) |
"""
77.Remove duplicates elements of the list withoud using built in keywords and temporary list.
"""
l=[1,2,3,4,3,5,6,3,7,4,5]
print "actual list:",l
def remove_duplicates(lst):
lst.sort()
i = len(lst) - 1
while i > 0:
if lst[i] == lst[i - 1]:
lst.pop(i)
i -= 1
return lst
print "list after removing duplicates:",remove_duplicates(l)
|
"""
72. create a user defined datatype, and provide functionalities of addition substraction and multiplication.
Create three instances(obj1,obj2,obj3) and print an output of obj1+obj2+obj3, obj1-obj2-obj3, obj1*obj2*obj3
"""
class userdeffun:
def __init__(self,x=0,y=0):
self.x=x
self.y=y
def __str__(self):
return "({0},{1})".format(self.x,self.y)
def __add__(self,other):
x = self.x + other.x
y = self.y + other.y
return userdeffun(x,y)
def __sub__(self,other):
x=self.x-other.x
y=self.y-other.y
return userdeffun(x,y)
def __mul__(self,other):
x=self.x*other.x
y=self.y*other.y
return userdeffun(x,y)
P1=userdeffun(6,7)
P2=userdeffun(4,5)
P3=userdeffun(3,2)
print (P1+P2+P3)
print (P1-P2-P3)
print (P1*P2*P3)
|
"""
80.WAP to remove perticular element from a given list for all occurancers
"""
s=[1,2,3,4,3,2]
print "main list:",s
m=[1,2]
print "sublist:",m
for i in s:
for i in s:
if i in m:
del s[s.index(i)]
print "after removing elements in sublist:",s
|
"""
52. keys=['k1','k2'], values = ['v1','v2'] form a dictionary
"""
keys=['k1','k2']
values=['v1','v2']
d={}
j=0
for i in keys:
d[i]=values[j]
j=+1
print d
|
#!/usr/bin/env python2
"""Text Widget/Automatic scrolling
This example demonstrates how to use the gravity of
`GtkTextMarks` to keep a text view scrolled to the bottom
while appending text.
"""
import pygtk
pygtk.require('2.0')
import gobject
import gtk
class AutomaticScrollingDemo(gtk.Window):
def __init__(self, parent=None):
# Create the toplevel window
gtk.Window.__init__(self)
try:
self.set_screen(parent.get_screen())
except AttributeError:
self.connect('destroy', lambda *w: gtk.main_quit())
self.set_title(self.__class__.__name__)
self.set_default_size(600, 400)
self.set_border_width(0)
hbox = gtk.HBox(True, 6)
self.add(hbox)
self.create_text_view(hbox, True)
self.create_text_view(hbox, False)
self.count_sb = 0
self.count_se = 0
self.show_all()
def create_text_view(self, hbox, scroll_to_end):
swindow = gtk.ScrolledWindow()
hbox.pack_start(swindow)
textview = gtk.TextView()
swindow.add(textview)
timeout = self.setup_scroll(textview, scroll_to_end)
# Remove the timeout in destroy handler, so we don't try to
# scroll destroyed widget.
textview.connect("destroy", lambda widget: gobject.source_remove(timeout))
def setup_scroll(self, textview, scroll_to_end):
buf = textview.get_buffer()
itr = buf.get_end_iter()
if scroll_to_end:
# If we want to scroll to the end, including horizontal scrolling,
# then we just create a mark with right gravity at the end of the
# buffer. It will stay at the end unless explicitely moved with
# gtk_text_buffer_move_mark.
buf.create_mark("end", itr, False)
# Add scrolling timeout.
return gobject.timeout_add(50, self.scroll_to_end, textview)
else:
# If we want to scroll to the bottom, but not scroll horizontally,
# then an end mark won't do the job. Just create a mark so we can
# use it with gtk_text_view_scroll_mark_onscreen, we'll position it
# explicitely when needed. Use left gravity so the mark stays where
# we put it after inserting new text.
buf.create_mark("scroll", itr, True)
# Add scrolling timeout.
return gobject.timeout_add(100, self.scroll_to_bottom, textview)
""" Scroll to the end of the buffer. """
def scroll_to_end(self, textview):
buf = textview.get_buffer()
# Get the "end" mark. It's located at the end of buffer because
# of right gravity
mark = buf.get_mark("end")
itr = buf.get_iter_at_mark(mark)
# and insert some text at its position, the iter will be
# revalidated after insertion to point to the end of inserted text
buf.insert(itr, "\n")
buf.insert(itr, " " * self.count_se)
buf.insert(itr, "Scroll to end scroll to end scroll to end scroll to end ")
# Now scroll the end mark onscreen.
textview.scroll_mark_onscreen(mark)
# Emulate typewriter behavior, shift to the left if we
# are far enough to the right.
self.count_se += 1
if self.count_se > 150:
self.count_se = 0
return True
""" Scroll to the bottom of the buffer. """
def scroll_to_bottom(self, textview):
buf = textview.get_buffer()
# Get the end iterator
itr = buf.get_end_iter()
# and insert some text at it, the iter will be revalidated
# after insertion to point to the end of inserted text
buf.insert(itr, "\n")
buf.insert(itr, " " * self.count_sb)
buf.insert(itr, "Scroll to bottom scroll to bottom scroll to bottom scroll to bottom")
# Move the iterator to the beginning of line, so we don't scroll
# in horizontal direction
itr.set_line_offset(0)
# and place the mark at iter. the mark will stay there after we
# insert some text at the end because it has right gravity.
mark = buf.get_mark("scroll")
buf.move_mark(mark, itr)
# Scroll the mark onscreen.
textview.scroll_mark_onscreen(mark)
# Shift text back if we got enough to the right.
self.count_sb += 1
if self.count_sb > 40:
self.count_sb = 0
return True
def main():
AutomaticScrollingDemo()
gtk.main()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python2
'''Buttons/Button 3
Toggle Buttons
Toggle buttons are derived from normal buttons and are very similar, except they will always be in one of two states,
alternated by a click. They may be depressed, and when you click again, they will pop back up.
Click again, and they will pop back down.
Toggle buttons are the basis for check buttons and radio buttons, as such, many of the calls used for toggle buttons
are inherited by radio and check buttons.
__Creating a new toggle button__:
`toggle_button = gtk.ToggleButton(label=None)`
These work identically to the normal button widget calls. If no label is specified the button will be blank.
The label text will be parsed for '_'-prefixed mnemonic characters.
To retrieve the state of the toggle widget, including radio and check buttons,
use a construct as shown below.
This tests the state of the toggle, by calling the `get_active()` method of the toggle button object.
The signal of interest to us that is emitted by toggle buttons (the toggle button, check button, and radio button
widgets) is the "toggled" signal.
To check the state of these buttons, set up a signal handler to catch the toggled signal, and access the object
attributes to determine its state. The callback will look something like:
`def toggle_button_callback(widget, data):`
`if widget.get_active():`
`# If control reaches here, the toggle button is down`
`else:`
`# If control reaches here, the toggle button is up`
To force the state of a toggle button, and its children, the radio and check buttons, use this method:
`toggle_button.set_active(is_active)`
The above method can be used to set the state of the toggle button, and its children the radio and check buttons.
Specifying a `True` or `False` for the `is_active` argument indicates whether the button should be down (depressed)
or up (released). When the toggle button is created its default is up or `False`.
Note that when you use the `set_active()` method, and the state is actually changed, it causes the `clicked` and
`toggled` signals to be emitted from the button.
`toggle_button.get_active()`
This method returns the current state of the toggle button as a boolean `True` or `False` value.
'''
import pygtk
pygtk.require('2.0')
import gtk
import os
IMAGEDIR = os.path.join(os.path.dirname(__file__), 'images')
ICON_IMAGE = os.path.join(IMAGEDIR, 'apple-red.png')
def callback(widget, data=None):
print "%s was toggled %s" % (data, ("OFF", "ON")[widget.get_active()])
class Button3Demo(gtk.Window):
def __init__(self, parent=None):
# Create the toplevel window
gtk.Window.__init__(self)
try:
self.set_screen(parent.get_screen())
except AttributeError:
self.connect('destroy', lambda *w: gtk.main_quit())
self.set_default_size(350, 100)
self.set_icon_from_file(ICON_IMAGE)
self.set_geometry_hints(min_width=100, min_height=100)
self.set_border_width(10)
vbox = gtk.VBox(True, 2)
self.add(vbox)
# Create first button
button = gtk.ToggleButton("toggle button 1")
# When the button is toggled, we call the "callback" method
# with a pointer to "button" as its argument
button.connect("toggled", callback, "toggle button 1")
# Insert button 1
vbox.pack_start(button, True, True, 2)
# Create second button
button = gtk.ToggleButton("toggle button 2")
# When the button is toggled, we call the "callback" method
# with a pointer to "button 2" as its argument
button.connect("toggled", callback, "toggle button 2")
# Insert button 2
vbox.pack_start(button, True, True, 2)
self.show_all()
def main():
Button3Demo()
gtk.main()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python2
"""Dialogs/D0
The Dialog widget is a window with a few things pre-packed into it for you.
It creates a window, and then packs a VBox into the top, which contains a separator and then an HBox called the "action_area".
Constructor is `gtk.Dialog`
It can be used for pop-up messages to the user and other similar tasks.
There is only one function for the dialog box:
`dialog = gtk.Dialog(title=None, parent=None, flags=0, buttons=None)`
where title is the text to be used in the titlebar, parent is the main application window and flags set various modes of operation for the dialog:
Flags:
`gtk.DIALOG_MODAL` - the dialog grabs all the keyboard events
`gtk.DIALOG_DESTROY_WITH_PARENT` - the dialog is destroyed when its parent is.
`gtk.DIALOG_NO_SEPARATOR` - there is no separator bar above the buttons.
The buttons argument is a `tuple` of button text and response pairs.
All arguments have defaults and can be specified using keywords.
"""
import pygtk
pygtk.require('2.0')
import gtk
import os
IMAGEDIR = os.path.join(os.path.dirname(__file__), 'images')
ICON_IMAGE = os.path.join(IMAGEDIR, 'gtk-logo.svg')
class D0Demo(gtk.Window):
def __init__(self, parent=None):
gtk.Window.__init__(self)
try:
self.set_screen(parent.get_screen())
except AttributeError:
self.connect('destroy', lambda *w: gtk.main_quit())
self.set_title(self.__class__.__name__)
self.set_default_size(200, 200)
self.set_icon_from_file(ICON_IMAGE)
self.set_geometry_hints(min_width=100, min_height=100)
label = gtk.Label("With label")
dialog = gtk.Dialog("gtk.Dialog", None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
dialog.vbox.pack_start(label)
label.show()
dialog.run()
dialog.destroy()
if __name__ == '__main__':
D0Demo()
gtk.main()
|
#!/usr/bin/env python2
'''Tree View/Model Tree 0
Basic Treeview connected to TreeStore.
The TreeView widget displays lists and trees displaying multiple columns.
It replaces the previous set of List, CList, Tree and CTree widgets with a much more powerful and flexible set of
objects that use the Model-View-Controller (MVC) principle to provide the following features:
two pre-defined models:
one for lists and one for trees
multiple views of the same model are automatically updated when the model changes
selective display of the model data
use of model data to customize the TreeView display on a row-by-row basis
pre-defined data rendering objects for displaying text, images and boolean data
stackable models for providing sorted and filtered views of the underlying model data
reorderable and resizeable columns
automatic sort by clicking column headers
drag and drop support
support for custom models (generic models) entirely written in Python
support for custom cell renderers entirely written in Python
'''
import pygtk
pygtk.require('2.0')
import gtk
class ModelTree0Demo(gtk.Window):
def __init__(self, parent=None):
gtk.Window.__init__(self)
try:
self.set_screen(parent.get_screen())
except AttributeError:
self.connect('destroy', lambda *w: gtk.main_quit())
self.set_title(self.__class__.__name__)
self.set_default_size(200, 200)
self.set_border_width(8)
# create a TreeStore with one string column to use as the model
treestore = gtk.TreeStore(str)
# we'll add some data now - 4 rows with 3 child rows each
for parent in range(4):
piter = treestore.append(None, ['parent %i' % parent])
for child in range(3):
treestore.append(piter, ['child %i of parent %i' %
(child, parent)])
# create the TreeView using treestore
treeview = gtk.TreeView(treestore)
# create the TreeViewColumn to display the data
tvcolumn = gtk.TreeViewColumn('Column 0')
# add tvcolumn to treeview
treeview.append_column(tvcolumn)
# create a CellRendererText to render the data
cell = gtk.CellRendererText()
# add the cell to the tvcolumn and allow it to expand
tvcolumn.pack_start(cell, True)
# set the cell "text" attribute to column 0 - retrieve text
# from that column in treestore
tvcolumn.add_attribute(cell, 'text', 0)
# make it searchable
treeview.set_search_column(0)
# Allow sorting on the column
tvcolumn.set_sort_column_id(0)
# Allow drag and drop reordering of rows
treeview.set_reorderable(True)
self.add(treeview)
self.show_all()
if __name__ == '__main__':
ModelTree0Demo()
gtk.main()
|
nums = [1,2,3,4,5,6]
#NORMAL METHOD USING FUNCTIOS:
# def square(n):
# return(n*n)
#USING LAMBDA FUNCTION:
print(list(map(lambda n: n*n ,nums)))
x = lambda a, b : a * b
print(x(5, 6))
|
names = ['raju','rani','pinky','sunny','baby']
for name in names:
print(name)
#Slicing using for loop56
for name in names[1:3]:
print(name)
for name in names:
if (name == 'pinky'):
print(f'{name}-Good girl')
# break
else:
print(name)
#WHILE LOOPS:
age = 25
num = 0
while(age>num):
print(num)
num += 1
|
# String Functions
# *******************
prem = "what are"
print(prem.replace("what","how"))
print(":".join(["apple","mango","banana"]))
print(prem.upper())
print(prem.lower())
print(prem.startswith("What"))
print(prem.isnumeric()) |
my_tuple = (1, 2, 3)
print(my_tuple[1])
my_other_tuple = (4,5,6)
my_tuple += my_other_tuple
x, y , z = my_tuple
|
##in fisierul 'ad.txt' se gasesc datele de intrare
##fisierul este de forma:
##stare_initiala Stari_finale
##cuvant cuvant cuvant......
##litera starea_din_care_pleaca starea_in_care_ajunge
##...
##litera starea_din_care_pleaca starea_in_care_ajunge
def parcurgere(lista, sir):
ok = True
point = 0 #pointeaza litera pana la acare s-a parcurs sirul
f = open("out.txt", "a")
f.write('Cuvantul: ' + str(sir) + '\n')
while (len(lista)!= [] and point<len(sir)):
f.write(str(lista) + ' ' + str(sir[point:]) + "\n") #scrie in fisier
print(str(lista) + ' ' + str(sir[point:])) #scrie in consola
lista = cautare(sir[point], lista, m)
if(lista == []):
ok = False
break
point = point+1
if(ok): #verifica daca starea in care s-a ajuns dupa parcurgerea cuvantului este finala
f.write(str(lista) + ' ' + "''\n") #scrie in fisier
print(str(lista) + ' ' + "''") #scrie in consola
ok = verificare(lista, final)
if(ok):
f.write(str(lista) + ' ' + "''\n")
print(str(lista) + ' ' + "''")
f.write('Cuvantul este acceptat!\n')
print('Cuvantul este acceptat!')
else:
f.write('Nu se poate!\n')
print('Nu se poate!')
f.write('\n')
f.close()
def cautare(litera, starea, text): #cauta starile a caror tranzitie accepta o litera anume
lista = []
for i in range(0, len(text.splitlines())):
for j in range(0, len(starea)):
if(text.splitlines()[i][0] == litera and text.splitlines()[i][2] == starea[j]):
lista.append(text.splitlines()[i][4])
return lista
def verificare(lista, final): #verifica daca cel putin una din starile in care a ajuns este stare finala
ok = False
for i in range(0, len(final)):
for j in range(0, len(lista)):
if (final[i] == lista[j]):
#print(str(final[i]) + ' == ' + str(lista[j] )) #debug
ok = True
return ok
f = open("in.txt", "r")
final = []
m = f.read()
start = m[0] #starea initiala
final = m.splitlines()[0][2:].split() #vector cu starile finale
f.close()
#ok = True
sir = m.splitlines()[1].split()
lista = [start]
#print('Stare initiala: ' + str(lista))
#print('Stari finale: ' + str(final))
f = open("out.txt", "w") #solutie simpla ptr a sterge un posibil vechi fisier "out.txt" si a creea unul nou in care se va face append
f.close()
for i in range(0, len(sir)):
print()
print(sir[i])
parcurgere(lista, sir[i]) |
def num_to_words(n): # supports up to 1000
if n == 1000:
return "one thousand"
if n >= 100:
if n % 100 == 0:
return f"{num_to_words(n // 100)} hundred"
return f"{num_to_words(n // 100)} hundred and {num_to_words(n % 100)}"
if n >= 20:
if n % 10 == 0:
return ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'][n // 10]
return f"{['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'][n // 10]}" \
f"-{num_to_words(n % 10)}"
return [
'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
][n]
def world_letter_count(s):
return len(s.replace(" ", "").replace("-", ""))
s = 0
for i in range(1, 1001):
s += world_letter_count(num_to_words(i))
if i < 25:
print(num_to_words(i))
print(s)
|
"""
47. Permutations II: Runtime: 40 ms, faster than 92.96%
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
Example 1:
Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]
Example 2:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
"""
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
nums.sort()
self.dfs(nums, [], res)
return res
def dfs(self, nums, path, res):
if len(nums) == 0:
res.append(path)
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i-1]:
continue
self.dfs(nums[:i] + nums[i+1:], path + [nums[i]], res) |
"""
在控制台中录入一个成绩,判断等级(优秀、良好、及格、不及格)
"""
def print_grade_level(grade_input):
"""
根据输入的成绩评判等级
:param grade_input: int 成绩
:return: 返回出对应的等级
"""
if int(grade_input)>100 or int(grade_input)<0:
return "成绩有误"
if int(grade_input) >= 90:
return"成绩优秀!"
if 75 <= int(grade_input):
return"成绩良好!"
if 60 <= int(grade_input) :
return"成绩合格!"
return"成绩不及格!"
grade =int(input("请输入成绩:"))
print(print_grade_level(grade)) |
#边界情况left与右的初始位置要与刚开始的时候相对应
#查找目标值
def get_target(nums, target):
left, right = 0, len(nums)#left为序列的开头,right为序列的末尾索引+1
while left < right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1 #下一轮迭代,left与right的位置与初始相同
else:
right = mid
return -1
#查找第一个不小于目标值的函数
#最后left+1=right,再进行一次迭代,left=right
def find_2(nums,target):
left,right=0,len(nums)
while left<right:
mid=left+(right-left)//2
if nums[mid]<target:
left=mid+1
else:
right=mid
return right
#查找第一个大于目标值的数
def find_3(nums,target):
left, right = 0, len(nums)
while left < right:
mid = left + (right - left) // 2
if nums[mid] <= target:
left = mid + 1
else:
right = mid
return right
nums=[0,1,1,2]
print(find_2(nums,target=2)) |
# -*- coding: utf-8 -*-
import re
import time
import sys
class Union(object):
def __init__(self, n):
# set count
self.time_counter = 0
self.ini_time = time.time()
self.count = n
# all numbers. when initialed, every number make a tree
self.id = list(xrange(n))
def connected(self, p, q):
# if p, q is connected, p, q is in the same tree
return self.find(p) == self.find(q)
def find(self, p):
while p != self.id[p]:
p = self.id[p]
return p
def union(self, p, q):
self.time_counter += 1
if not self.time_counter % 100:
print "data count: {}, time cost: {}".format(self.time_counter, time.time() - self.ini_time)
p_id = self.find(p)
q_id = self.find(q)
# if p, q is not connect, make p_id equal q_id, which means q is the root of p
if not self.connected(p, q):
self.id[p_id] = q_id
self.count -= 1
FILE_NAME_TO_NUMBER = {
'tinyUF.txt': 10,
'mediumUF.txt': 625,
'largeUF.txt': 1000000
}
un = Union(FILE_NAME_TO_NUMBER[sys.argv[1]])
t1 = time.time()
with open(sys.argv[1], 'rb') as r:
for line in r:
(p, q) = re.split('\s+', line.rstrip())
p = int(p)
q = int(q)
un.union(p, q)
# print 'id of list'
# `print un.id
print 'set count: {}'.format(un.count)
t2 = time.time()
print "time cost: {}".format(t2 - t1)
|
from typing import List, TypeVar
T = TypeVar('T', int, float, str)
def minimum(array: List[T]) -> int:
min_el = array[0]
for i in range(1, len(array)):
if min_el > array[i]:
min_el = array[i]
return min_el
|
from typing import TypeVar, List
T = TypeVar('T', int, str, float)
def linear_search(array: List[T], key: T) -> int:
for i in range(len(array)):
if array[i] == key:
return i
return -1
|
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 27 19:19:45 2018
@author: Lucy
"""
'''
__str__
'''
class Student(object):
def __init__(self,name):
self.name=name
def __str__(self):
return 'Student object (name:%s)' % self.name
__repr__=__str__
'''
怎么才能打印得好看呢?
只需要定义好__str__()方法,返回一个好看的字符串就可以了:
'''
s=Student('Michael')
'''
__iter__
如果一个类想被用于for ... in循环,类似list或tuple那样,
就必须实现一个__iter__()方法,该方法返回一个迭代对象,
然后,Python的for循环就会不断调用该迭代对象的__next__()方法拿到循环的下一个值,
直到遇到StopIteration错误时退出循环。
'''
class Fib(object):
def __init__(self):
self .a,self.b=0,1
def __iter__(self):
return self
def __next__(self):
self.a,self.b=self.b,self.a+self.b
if self.a>10000:
raise StopIteration()
return self.a
#表现得像list那样按照下标取出元素,需要实现__getitem__()方法:
#现在,就可以按下标访问数列的任意一项了
def __getitem__(self,n):
a,b=1,1
for x in range(n):
a,b=b,a+b
return a
#实现类似List的切片操作
'''
def __getitem__(self,n):
if isinstance(n,int):
a,b=1
for x in range(n):
a,b=b,a+b
return a
if isinstance(n,slice):
start=n.start
stop=n.stop
if start is None:
start=0
a,b=1,1
L=[]
for x in range(stop):
if x>=start:
L.append[a]
a,b=b,a+b
return L
'''
'''
当类的属性不存在,但是还是调用的时候,使用 __getattr__
'''
def __getattr__(self,attr):
if attr=='score':
return 99
#不存在score属性,此时默认值是99,并发出警报,说明Student类没有改属性
raise AttributeError('\'Student object has no attribute\'%s\'' % attr)
#定义一个Student
class Student(object):
def __init__(self,name):
self.name=name
'''
一个对象实例可以有自己的属性和方法,当我们调用实例方法时,
我们用instance.method()来调用。能不能直接在实例本身上调用呢?
在Python中,答案是肯定的
'''
def __call__(self):
print('MY name is %s' %self .name)
s=Student('Michael')
'''
怎么判断一个变对象是能被调用?---使用Callable()
'''
|
# -*- coding:utf-8 -*-
from collections import deque #双端队列
dequeQueue = deque(['Eric','John','Smith'])
print(dequeQueue)
dequeQueue.append('Tom') #在右侧插入新元素
dequeQueue.appendleft('Terry') #在左侧插入新元素
print(dequeQueue)
dequeQueue.rotate(2) #循环右移2次
print(dequeQueue)
while len(dequeQueue) > 0 :
print(dequeQueue.popleft())
a =[1,2,3,4]
a.append(5)
print(a)
a.pop()
print(a) |
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
d = dict()
for i in nums:
if d.get(i):
return True
else:
d[i]= 1
return False
t = [1,2,3,1]
s = Solution()
r = s.containsDuplicate(t)
print(r) |
"""
Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns true
Note:
You may assume that all inputs are consist of lowercase letters a-z.
All inputs are guaranteed to be non-empty strings.
"""
import collections
class TrieNode:
def __init__(self):
self.children = dict()
# self.char_str = None
self.is_word = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
p = self.root
for i in word:
if p.children.get(i) is None:
a = TrieNode()
a.char_str = i
p.children[i] = a
p = p.children[i]
p.is_word = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
p = self.root
for letter in word:
p = p.children.get(letter)
if p is None:
return False
return p.is_word
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
p = self.root
for letter in prefix:
p = p.children.get(letter)
if p is None:
return False
return True
# Your Trie object will be instantiated and called as such:
word = "apple"
prefix = "app"
obj = Trie()
obj.insert(word)
param_2 = obj.search(word)
print(param_2)
print(obj.search("aaa"))
param_3 = obj.startsWith(prefix)
print(param_3)
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def maxDepth(self, root: TreeNode) -> int:
return self.visitNode(root)
def visitNode(self, root:TreeNode) -> int:
print("visit:",root.val)
if root is None:
return 0
else:
if root.left is None and root.right is None:
return 1
else:
left_depth = self.visitNode(root.left)
right_depth = self.visitNode(root.right)
currNodedepth = max(left_depth, right_depth) + 1
return currNodedepth
s = Solution()
root = TreeNode(3)
node9 = TreeNode(9)
node20 = TreeNode(20)
node15 = TreeNode(15)
node7 = TreeNode(7)
node20.left = node15
node20.right = node7
root.left = node9
root.right = node20
b = s.maxDepth(root)
print(b)
|
'''
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Example:
Input:
"abccccdd"
Output:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
'''
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
d = dict()
even_num = 0
odd_num = 0
for i in s:
count = d.get(i, 0)
count = count + 1
if count == 2:
d[i] = 0
even_num = even_num + 1
odd_num = odd_num - 1
else:
d[i] = count
odd_num = odd_num + 1
if odd_num == 0:
return even_num * 2
else:
return even_num * 2 + 1
def longestPalindrome2(self, s):
"""
:type s: str
:rtype: int
"""
import collections
odds = sum(v & 1 for v in collections.Counter(s).values())
center = 0
if odds != 0:
center = 1
return len(s) - odds + center
s = Solution()
num = s.longestPalindrome2("abccccdd")
num = s.longestPalindrome2("bbbb")
print(num)
|
'''
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Note:
You may assume the string contains only lowercase alphabets.
'''
from collections import Counter
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
print(len(s),len(t))
if len(s) == len(t):
counter = Counter(s)
counter2 = Counter(t)
flag = True
for i in counter:
if counter.get(i) != counter2.get(i):
flag = False
return flag
else:
return False
s = Solution()
s.isAnagram("sdfa","afds") |
# -*- coding:utf-8 -*-
# 最大公约与最小公倍
#
def max_yue(number1:int, number2:int):
if number1 < number2:
temp = number1
number1 = number2
number2 = temp
m=number1; n=number2;
while( m%n !=0):
r = m % n
m = n
n = r
print("最大公约数:{}".format(n))
print("最小公倍数:{}".format(number1*number2//n))
max_yue = n
min_bei = number1*number2//n
return max_yue, min_bei
b = max_yue(49,35)
print(b) |
country = input("What is your country? ").capitalize()
tax = 0
if country == "Canada":
province = input("What is your province? ").capitalize()
if province in ("Alberta", "Nunavut", "Yukon"):
tax = 0.05
elif province == "Ontario":
tax = 0.13
else:
tax = .15
print("Your province tax rate is: ", tax)
else:
print("You don not need to pay tax!")
|
#this is straight up code from I believe CodeCademy.com
from node import Node
def type(name, content, endDate):
table = name + ' ' + content.ljust(20) + endDate
return table
class LinkedList:
def __init__(self, name, content, endDate=None, next_node=None):
self.head_node = Node(name, content, endDate, next_node)
def get_head_node(self):
return self.head_node
def insert_beginning(self, new_name, new_content, new_endDate=None):
new_node = Node(new_name, new_content, new_endDate)
new_node.set_next_node(self.head_node)
self.head_node = new_node
def stringify_list(self):
string_list = ""
current_node = self.get_head_node()
while current_node:
if current_node.get_name() != None:
string_list += str(current_node.get_name()) + "-" + str(current_node.get_content())
if current_node.get_endDate() != None:
string_list += " End Date: " + str(current_node.get_endDate())
string_list += "\n"
current_node = current_node.get_next_node()
return string_list
def remove_node(self, endDate):
current_node = self.get_head_node()
while current_node.get_endDate() == endDate:
self.head_node = current_node.get_next_node()
current_node = self.get_head_node()
while current_node:
if current_node.get_next_node() != None:
next_node = current_node.get_next_node()
if next_node.get_endDate() == endDate:
current_node.set_next_node(next_node.get_next_node())
elif next_node.get_name() != None:
current_node = next_node
else:
current_node = None
|
'''
an automated bruteforce attack on a shift cipher
@author: Willi Schoenborn
'''
from LetterFrequency import LetterFrequency
from string import upper
import sys
def main():
if len(sys.argv) is 1:
filename = '../resources/hinter-den-wortbergen.txt'
else:
filename = sys.argv[1]
textfile = open(filename, 'r')
ciphertext = textfile.read()
textfile.close()
dictionaryfile = open('../resources/ngerman', 'r')
dictionary = set(upper(dictionaryfile.read()).split("\n"))
dictionaryfile.close()
frequencies = map(lambda key:LetterFrequency(ciphertext, key) , range(26))
frequencies = sorted(frequencies, key=LetterFrequency.average_deviation)
max_wordlength = 25
length = len(ciphertext)
limit = length * 1/3
def find():
for frequency in frequencies:
text = frequency.shift(ciphertext)
limit = length * 1/3
words = []
letters = 0
start = 0
end = 1
while start < length:
word = text[start:end]
if word in dictionary:
words.append(word)
letters += len(word)
if letters > limit:
return frequency
start = end
end += 1
if end > length or end - start > max_wordlength:
start += 1
end = start + 1
return None
best = find()
if best is None:
print "Nothing found"
else:
print "Encryption key is %s" % best.key
print best.shift(ciphertext)
if __name__ == '__main__':
main()
|
# Archivo: pinta_parabola.py
# Autor: Javier Garcia Algarra
# Fecha: 24 de diciembre de 2017
# Descripción: Dibujamos una circunferencia
import matplotlib.pyplot as plt
import math # importamos la librería matemática que sabe hacer raíces cuadradas
# Funcion para crear una lista de numeros que empieza en inferior y termina en superior
def crea_lista_de_valores(inferior, superior):
listadevalores = [] # Creamos una lista vacia
for j in range(inferior,superior+1): # La variable j va tomando los valores del rango inferior a superior
listadevalores.append(j) # Cada valor de la variable j se añade a la lista
return(listadevalores) # Se devuelve la lista completa
# Crear una lista de números naturales, del -9 al 9
x_valores = crea_lista_de_valores(-9,9)
# Ahora vamos a crear los valores y. La formula de la circunferencia es y**2 + x**2 = radio**2
# Recorremos los valores de x para crear otra lista de valores y
# pero para cada valor de x hay dos valores de y, el positivo y el negativo de la raiz cuadrada.
# Para solucionarlo creamos dos listas de valores y, una positiva y otra negativa
radio = 9
y_valores_pos = []
y_valores_neg = []
for k in x_valores:
y_valores_pos.append(math.sqrt(radio**2 - k**2))
y_valores_neg.append(-math.sqrt(radio**2 - k**2))
# Parte del programa que pinta la gráfica. Pasamos a la funcion plt.plot las listas de valores x e y
plt.plot(x_valores, y_valores_pos, ".")
plt.plot(x_valores, y_valores_neg, ".") # Añadimos la lista de valores y negativos al gráfico
plt.axis('equal')
plt.ylabel('y') # Etiqueta del eje y. Podriamos no ponerla
plt.xlabel('x') # Etiqueta del eje x
plt.show() # Esta función ordena mostrar la imagen en una ventanita nueva
|
x=int(input("enter 1st value:"))
y=int(input("enter 2nd value:"))
z=int(input("enter 3rd value:"))
def fun(x,y,z):
if(x>y):
if(x>z):
print(x," is greatest")
else:
print(z," is greatest")
elif(y>z):
print(y," is greatest")
else:
print(z," is greatest")
fun(x,y,z)
#Output :
#enter 1st value:7
#enter 2nd value:5
#enter 3rd value:6
#7 is greatest
|
class Solution:
def sortArray(self, nums):
"""
:type nums:List[int]
:rtype: List[int]
"""
if len(nums) <= 1:
return nums
mid_point = int(len(nums) / 2)
left, right = self.sortArray(
nums[:mid_point]), self.sortArray(nums[mid_point:])
return merge(left, right)
def merge(left, right):
result = []
left_pointer = right_pointer = 0
while left_pointer < len(left) and right_pointer < len(right):
if left[left_pointer] < right[right_pointer]:
result.append(left[left_pointer])
left_pointer += 1
else:
result.append(right[right_pointer])
right_pointer += 1
result.extend(left[left_pointer:])
result.extend(right[right_pointer:])
return result
|
class Solution:
def reverse(self, x: int) -> int:
value = str(x)
new_str = ''
num = 0
if x == 0:
return 0
elif x < 0:
if value.__contains__('0'):
value = value.strip('0')
value = value[1:]
for i in range(len(value)-1, -1, -1):
new_str = new_str + value[i]
new_str = '-' + new_str
num = int(new_str)
elif x > 0:
if value.__contains__('0'):
value = value.strip('0')
for i in range(len(value)-1, -1, -1):
new_str = new_str + value[i]
num = int(new_str)
neg_limit = -0x80000000
pos_limit = 0x7fffffff
if num < 0:
val = num & neg_limit
if val == neg_limit:
return num
else:
return 0
elif num == 0:
return 0
else:
val = num & pos_limit
if val == num:
return num
else:
return 0
|
import random
from random import randint
import os
import os.path
flag1=True
flag2=True
flag3=True
flag4=True
flag5=True
flag6=True
class player:
player_name = "Bot"
player_nprizes =2
player_money = 100.0
player_prize="book,pen"
def set_player_details(self,name, nprizes, money,prize):
self.player_name = name
self.player_nprizes = nprizes
self.player_money = money
self.player_prize=prize
fw = open(self.player_name, 'w')
fw.write(self.player_name+" "+str(self.player_nprizes)+" "+str(self.player_money)+"\n")
fw.write(self.player_prize)
fw.close()
def get_player_details(self):
print("Player Name:"+self.player_name)
print("Player No of Prizes:"+str(self.player_nprizes))
print("Player Money:"+str(self.player_money))
print("Player Prize Won:"+str(self.player_prize))
def send_player_money(self):
return self.player_money
def send_player_name(self):
return self.player_name
def send_player_nprizes(self):
return self.player_nprizes
def send_player_prize(self):
return self.player_prize
class lucky_number_generator(player):
def generate_number(self):
lucky_number = randint(1, 5)
return lucky_number
class Game(player, lucky_number_generator):
def gamy(self):
while self.flag4:
try:
self.amount=raw_input("Enter The Amount For Which You Wanna Play in Range{1-5]:")
self.flag4=False
except:
print("Enter a valid Amount")
continue
if self.amount > self.player_money:
print("You Don't Have That Much Money")
else:
self.player_money=self.player_money-self.amount
playerobj = lucky_number_generator()
while True:
frs = open('start', 'r')
start = frs.read()
print start
frs.close()
flag1=True
flag2=True
flag3=True
flag4=True
flag5=True
try:
choice = int(input("Select an option : "))
flag6=False
except:
print("Enter A Valid Choice")
continue
if choice == 1:
print("Enter Player details")
while flag1:
player_name = raw_input("Enter player name :" )
if player_name=="":
print("Enter a valid name")
else:
flag1=False
PATH='./'+player_name
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
print "Welcome Back "+player_name+"..."
with open(player_name, 'r') as myfile:
data=myfile.readline()
data1=myfile.readline()
list=data.split(" ")
player_nprizes=int(list[1])
player_money=float(list[2])
player_prize=data1
else:
print "Hello "+player_name+"..."
player_prize=""
while flag2:
try:
player_nprizes = int(raw_input("Enter No. of Prizes : "))
flag2=False
except:
print("Enter a valid No. of Prizes")
continue
while flag3:
try:
player_money = float(raw_input("Enter Total money player has : "))
flag3=False
except:
print("Enter a valid Amount")
continue
playerobj.set_player_details(player_name, player_nprizes, player_money,player_prize)
elif choice == 2:
guess=0
amount=0
# objgame.gamy()
pl=playerobj.send_player_money()
pz=playerobj.send_player_nprizes()
pn=playerobj.send_player_name()
p=playerobj.send_player_prize()
print ("You have: "+str(pl)+"Rs")
if (pl>0):
while flag4:
try:
amount=float(raw_input("Enter The Amount For Which You Wanna Play in Range[1-5]:"))
if amount > pl:
print("You Don't Have That Much Money")
continue
elif amount >5:
print("Please Enter amount in range 1 to 5")
continue
else:
pl=pl-amount
print pl
playerobj.set_player_details(pn,pz,pl,p)
flag4=False
except:
print("Enter a valid Amount")
continue
while flag5:
try:
guess=int(raw_input("Guess A Number in range [1-5] :"))
flag5=False
except:
print("Enter a valid Guess")
continue
lucky=playerobj.generate_number()
print "Lucky Number Was:"+str(lucky)
if guess==lucky:
if amount==1:
print("Congratulation You Won The Pen")
pl=pl+10
pz=pz+1
p= p + ' pen'
elif amount==2:
print("Congratulation You Won The Book")
pl=pl+20
pz=pz+1
p= p + ' book'
elif amount==3:
print("Congratulation You Won The DVD")
pl=pl+30
pz=pz+1
p= p + ' DVD'
elif amount==4:
print("Congratulation You Won The Mouse")
pl=pl+40
pz=pz+1
p= p + ' mouse'
elif amount==5:
print("Congratulation You Won The Keyboard")
pl=pl+50
pz=pz+1
p= p + ' keyboard'
else:
print("You Lost This Game Try Again..")
playerobj.set_player_details(pn,pz,pl,p)
else:
print("No balance")
elif choice == 3:
playerobj.get_player_details()
elif choice == 4:
print("Help center")
print("Price List: ")
fr = open('Game_help.txt', 'r')
text = fr.read()
print(text)
fr.close()
print("Game Rules: ")
print("1. Admin will set up a new player by setting his name, money, prizes, etc.")
print("2. Is the player exists he will get is previous data from the file otherwise a new player would be created.")
print("3. The player will than select the amount for which he/she wants to play.")
print("4. The player than has to guess a number and if the guess is correct, "
"he/she will a prize worth 10 times the amount he played for.")
print("5. If the guess is wrong player will loose that much amount.")
elif choice == 5:
exit(0)
else:
print("Enter a Valid Choice")
continue
|
def logicaFibonacci (op):
numUno = 0
numDos = 1
numSop = 0
detener = True
print(numUno)
print(numDos)
while detener:
numSop = numUno + numDos
print(numSop)
numUno = numDos
numDos = numSop
if ( op <= numSop ):
detener = False
def validarValor (valor):
try:
return int (valor)
except ValueError:
print ("Debe ingresar solo números")
return "errorNumeros"
print("Gracias por utilizar nuestro Programa")
num = validarValor ( input ("Ingrese un valor para mostrar la serie de Fibonacci:\n"))
if ( num != "errorNumeros"):
if ( num <= 0):
print ("La suseccion de Fibonacci empieza desde el 0 por ejemplo:")
logicaFibonacci(2)
else:
logicaFibonacci (num) |
arr=[1,2,3,0]
def Min(arr):
cont=arr[0]
for i in arr:
if i<cont:
cont=i
print('минимум в массиве =',cont)
Min(arr)
def Arif(arr):
sum=0
count=len(arr)
for i in arr:
sum+=i
sr=sum/count
print('среднее арифметическое в массиве =',sr)
Arif(arr)
string='hello, world'
def Swap(string):
c=len(string)-1
arr2=''
for i in string:
arr2+=string[c]
c-=1
print(arr2)
Swap(string)
ivan={
"name":"ivan",
"age":34,
"children":[{
"name":"vasja",
"age":15,
},{
"name":"petja",
"age":10,
}],
}
darja={
"name":"darja",
"age":41,
"children":[{
"name":"kirill",
"age":21,
},{
"name":"pavel",
"age":19,
}],
}
emps=[ivan,darja]
for i in emps:
a=i.get('children')
for q in a:
if q.get('age')>18:
print(i.get('name'))
break
|
# initialization
pentagonal = []
n = 1
res = []
tested = []
while n < 10: # reasonable number
pentagonal.append(n*(3*n-1)/2)
for e in pentagonal:
for p in pentagonal:
if [e,p] in tested:
continue
if (e+p) in pentagonal:
if (e-p) or (p-e) in pentagonal:
print [e,p]
break
else:
tested.append([e,p])
else:
tested.append([e,p])
n += 1 |
import random
def isPrime(number):
for x in range (2,int(number**0.5+1)):
if (number % x == 0):
return False
return True
def factorial(tralala):
total = 1
while tralala > 0:
total *= tralala
tralala -= 1
return total
def counts(options):
count = []
for p in options:
if p not in count:
count.append(p)
return count
def rotation(lala):
global primes
options = []
for char in range(0,len(lala)):
options.append(lala[char])
count = counts(options) # factorial is only of unique elements, but options must contain everything
if ('0' in count) or ('2' in count) or ('4' in count) or ('6' in count) or ('8' in count) or ('5' in count):
return False
results = []
while len(results) < factorial(len(count)):
m = options[:]
z = random.choice(m)
m.remove(z)
while len(z) < len(options):
y = random.choice(m)
m.remove(y)
z += y
if int(z) not in primes: # might be faster if primes is generated all at once, rather than repeated testing
return False
if z not in results:
results.append(z)
for finalcheck in results:
if int(finalcheck) not in primes:
return False
return True
res = [2,5]
primes = [1,2,3]
for n in range(5,1000000,2):
if isPrime(n):
primes.append(n)
for e in primes:
if rotation(str(e)):
res.append(e)
print len(res)-1
print res |
def digit_addition(n):
pos = 0
total = 0
n = str(n)
while pos < len(n):
digit = int(n[pos])
total += digit
pos += 1
return total
n = 100
product = 1
while n > 0:
product = product * n
n += -1
print digit_addition(product) |
#n46
def prime(i):
if i%2==0: return False
for j in range(3,int(i**0.5)+1,2):
if i%j==0: return False
return True
def goldbach(m):
global primes
for n in primes:
if (((m-n)/2)**0.5).is_integer():
return False
return True
x = 3
primes = []
#composites = []
while True:
if prime(x):
primes.append(x)
else:
if goldbach(x):
print x
break
x+=2
# composites.append(x)
|
# initialization
n = 0
count = 0
irrational = 0
while float(len(str(irrational))) < 15:
n += 1
count += 1
irrational += n*(-10**(count-int(len(str(n)))+1)
if float(len(str(irrational))) > 10.0 :
a = int(str(irrational)[12])
print a |
def digiNext(n):
next = 0
for digitpos in range(0, int(len(str(n)))): #taken from 30.py
next += int((str(n))[digitpos])
return next
largest = 0
for a in range(1, 100):
for b in range(1, 100):
test = a**b
result = digiNext(test)
if result >= largest:
largest = result
print largest |
def selection_sort(a):
for i in range(0, len(a)-1):
min_idx = i
for j in range(i+1, len(a)):
if a[j] < a[min_idx]:
min_idx = j
a[i], a[min_idx] = a[min_idx], a[i] #python은 그냥 된다 swap
ls = [1,5,8,3,5,7,3]
selection_sort(ls)
print(ls) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import datetime
__DATE__ = 2016 / 10 / 10
__author__ = "ban"
__email__ = "bcan@shou.edu.cn"
__version__ = "1.0"
# start_time=np.array(Ptime(time[0],'mjulian').Format('mpl'))+TimeZone/24.0
# ptime_obs=Ptime(ptime_obs.Format('mjulian')-8.0/24.0,'mjulian')
class Ptime:
"""The date time in various styles transform class.
The core is the python datetime object , different types firstly trans to datetime object.
Then process and output in different format.
Vars:
time_data : The input time data in original type.
type : The input time data type , this is specified by users.
Time : The time data in python datetime type. This is the core data
Methods:
parse_time: parse the time data to datetime object
input : time_data flag
format : output the time in Format.
input : type
"""
def __init__(self, time_data, style='', debug=0):
self.debug = debug
self.time_data = time_data
self.style = style
self.Time = self.parse_time
try:
self.ntime = len(self.Time)
except TypeError:
self.ntime = 1
def __repr__(self):
return 'ptime({:})'.format(self.Time)
def __len__(self):
return len(self.Time)
def __getitem__(self, position):
return Ptime(self.Time[position])
def __add__(self, other):
time = np.concatenate((self.Time, other.Time))
return Ptime(time)
@property
def parse_time(self, ):
if not self.style:
times = self.time_data
elif self.style.find("delta") != -1:
times = parse_delta(self.time_data)
elif self.style.find("str") != -1 or self.style.find('%') != -1 or self.style.find("FVCOM") != -1:
if self.style.find("str") != -1:
fmt = "%Y-%m-%d_%H:%M:%S"
elif self.style.find("FVCOM") != -1:
fmt = "%Y-%m-%dT%H:%M:%S"
else:
fmt = self.style
if isinstance(self.time_data, str):
times = datetime.datetime.strptime(self.time_data, fmt)
else:
times = []
for itime in self.time_data:
time_elem = datetime.datetime.strptime(itime, fmt)
times.append(time_elem)
times = np.asarray(times)
elif self.style.find("range") != -1:
if isinstance(self.time_data[0], datetime.datetime):
time_start = self.time_data[0]
else:
time_start = Ptime(self.time_data[0], 'str').Time
if isinstance(self.time_data[1], datetime.datetime):
time_stop = self.time_data[1]
else:
time_stop = Ptime(self.time_data[1], 'str').Time
time_delta = datetime.timedelta(hours=float(self.time_data[2]))
times = time_range2list(time_start, time_stop, time_delta)
else:
if isinstance(self.time_data, (float, np.float, np.float32, np.float64)):
times = parse_time_from_floatformat(self.time_data, self.style)
else:
times = []
for itime in self.time_data:
time_elem = parse_time_from_floatformat(itime, self.style)
times.append(time_elem)
times = np.asarray(times)
return times
def format(self, style):
""" Output date and time in different format.
Need to specify the output style, Support these styles currently:
str format:
default :
FVCOM_str :
json-str :
user defined by "%"
float format:
mjulian, matlab, mpl
ncep, ECMWF
Note: if you want python datetime format, just use ptime.Time.
"""
# force all input data to array
# TypeError: iteration over a 0-d array
if type(self.Time) == datetime.datetime:
times = np.array([self.Time])
else:
times = self.Time
# ------------ for str format --------------
# the time_out array's dtype must specify the length, just like 26
# 'S' in python3 and numpy 1.13 means bytes, for compatible with py2.
# so the correct dtype should be U26
if style.find('str') != -1:
time_out = np.empty_like(times, dtype='U26')
if style is 'FVCOM_str':
time_str_format = "%Y-%m-%dT%H:%M:%S.%f..."
elif style is 'json_str':
# 2016-01-01T00:00:00.000Z
time_str_format = "%Y-%m-%d_%H:%M:%S.%fZ"
else:
time_str_format = "%Y-%m-%d_%H:%M:%S..." # '...' for [:-3]
for i, itime in enumerate(times):
time_out[i] = str(itime.strftime(time_str_format))[:-3]
elif style.find('%') != -1:
time_out = np.empty_like(times, dtype='U48')
for i, itime in enumerate(times):
time_out[i] = datetime.datetime.strftime(itime, style)
else:
time_out = np.empty_like(times, dtype=np.float64)
for i, itime in enumerate(times):
time_out[i] = floatformat_time(itime, style)
if len(time_out) == 1:
time_out = time_out[0]
return time_out
def format_fvcom(self, ):
""" format the ptime to tide format.
tide time format has 4 elements: iint,time,itime,itime2,times
iint is the time index, just set it to zero.
time is mjulian float format.
itime is the int part of mjulian float time
itime2 is the decimal part of mjulian float time
the mjulian float format time should be doule-float,
while the result of tide is stored by single-float data type.
so need two int(itime,itime2) to store the mjulian time.
"""
iint = np.zeros_like(self.Time, dtype=int)
time = self.format('mjulian')
itime = np.floor(time)
# 1000 millisecond = 1 second
itime2 = (time - itime) * 24 * 60 * 60 * 1000
times = self.format("FVCOM_str")
return iint, time, itime, itime2, times
def parse_time_from_floatformat(time_data, kind='mjulian'):
if kind is 'mjulian':
"""mjulian dates are relative to 1858/11/17 00:00:00 and stored in days.
"""
time_zero = datetime.datetime(1858, 11, 17, 0, 0, 0)
time_delta = datetime.timedelta(days=np.float64(time_data))
elif kind is 'matlab':
"""MATLAB's dates are relative to 0000/01/00 00:00:00 and stored in days.
as python datetime minyear=1.trans it to mjulian , the diff is 678942.0
"""
time_zero = datetime.datetime(1858, 11, 17, 0, 0, 0)
time_delta = datetime.timedelta(days=np.float64(time_data - 678942.0))
elif kind is 'gregorian':
time_zero = datetime.datetime(1950, 1, 1, 0, 0, 0)
time_delta = datetime.timedelta(days=np.float64(time_data))
elif kind is 'excel':
""" excel dates are relative to 1900/01/01 00:00:00 and stored in days.
"""
time_zero = datetime.datetime(1900, 1, 1, 0, 0, 0)
time_delta = datetime.timedelta(days=np.float64(time_data))
elif kind is 'ncep':
"""ncep dates are relative to 1800/01/01 00:00:00 and stored in hours.
"""
time_zero = datetime.datetime(1800, 1, 1, 0, 0, 0)
time_delta = datetime.timedelta(hours=np.float64(time_data))
elif kind is 'ECMWF':
""" ECMWF dates are relative to 1900/01/01 00:00:00 and stored in hours.
"""
time_zero = datetime.datetime(1900, 1, 1, 0, 0, 0)
time_delta = datetime.timedelta(hours=np.float64(time_data))
elif kind is 'noaa':
time_zero = datetime.datetime(1981, 1, 1, 0, 0, 0)
time_delta = datetime.timedelta(seconds=np.float64(time_data))
else:
"""default is mjulian"""
time_zero = datetime.datetime(1858, 11, 17, 0, 0, 0)
time_delta = datetime.timedelta(days=np.float64(time_data))
return time_zero + time_delta
def parse_delta(time_data):
time_delta = datetime.timedelta(hours=time_data)
# Time_delta = datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
return time_delta
def time_range2list(time_start, time_end, time_delta):
times_list = []
itime = time_start
while itime <= time_end:
times_list.append(itime)
itime = itime + time_delta
times = np.array(times_list, dtype=datetime.datetime)
return times
def floatformat_time(time_data, kind):
if kind.startswith('m'):
# give the modify julian time_zero
time_zero = datetime.datetime(1858, 11, 17, 0, 0, 0)
times_m = float((time_data - time_zero).days) + \
((float((time_data - time_zero).seconds) / 3600.0) / 24.0)
if kind is 'matlab':
times = times_m + 678942.0
elif kind is 'mpl':
times = times_m + 678576.0
else:
times = times_m
elif kind.startswith('ncep'):
time_zero = datetime.datetime(1800, 1, 1, 0, 0, 0)
times = (time_data - time_zero).days * 24. + (time_data - time_zero).seconds / 3600.0
elif kind.startswith('ECMWF'):
time_zero = datetime.datetime(1900, 1, 1, 0, 0, 0)
times = (time_data - time_zero).days * 24. + (time_data - time_zero).seconds / 3600.0
else:
times = time_data
return times
def get_coincide_time(ptime_model, ptime_obs, debug=0):
index_model = []
index_obs = []
coincide_time = []
for i, itime_model in enumerate(ptime_model.Time):
for j, jtime_obs in enumerate(ptime_obs.Time):
if itime_model == jtime_obs:
index_model.append(i)
index_obs.append(j)
coincide_time.append(itime_model)
index_model = np.asarray(index_model)
index_obs = np.asarray(index_obs)
coincide_time = np.asarray(coincide_time)
return index_model, index_obs, coincide_time
def get_match_time(ptime_model, ptime_obs, method='datetime'):
if method == 'datetime':
time_start = max(ptime_model.Time[0], ptime_obs.Time[0])
time_stop = min(ptime_model.Time[-1], ptime_obs.Time[-1])
bool_model = np.all([ptime_model.Time > time_start, ptime_model.Time < time_stop], axis=0)
bool_obs = np.all([ptime_model.Time > time_stop + 0.003, ptime_model.Time < time_stop - 0.003], axis=0)
index_model = np.arange(len(ptime_model.Time))[bool_model]
index_obs = np.arange(len(ptime_obs.Time))[bool_obs]
time_wanted = ptime_model.Time[bool_model]
elif method == 'mjulian':
time_model = ptime_model.format('mjulian')
time_obs = ptime_obs.format('mjulian')
times = max(time_model[0], time_obs[0])
time_stop = min(time_model[-1], time_obs[-1])
# 0.0015 for model time single precision
# bool_model=np.all([time_model>=times,time_model<=timee], axis=0)
# bool_obs=np.all([time_obs>=times,time_obs<=timee], axis=0)
bool_model = np.all([time_model > times + 0.003, time_model < time_stop - 0.003], axis=0)
bool_obs = np.all([time_obs > times + 0.003, time_obs < time_stop - 0.003], axis=0)
index_model1 = np.arange(len(time_model))
index_obs1 = np.arange(len(time_obs))
index_model = index_model1[bool_model]
index_obs = index_obs1[bool_obs]
time_wanted = time_model[bool_model]
else:
index_model = index_obs = time_wanted = []
return index_model, index_obs, time_wanted
|
name=input('请输入您的姓名:')
hoppy=input('请输入您的爱好:')
print('您输入的姓名为:'+name+',您的爱好为:'+hoppy)
print('您输入的姓名为:',name,',您的爱好为:',hoppy)
print('您输入的姓名为:%s,您的爱好为:%s'%(name,hoppy))
print('您输入的姓名为:%s'%name)
print('您的爱好为:%s'%hoppy)
|
# for循环
# 计算1~10内所有数字的相加之和
sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
sum += x
print('相加之和为:%s' % sum)
|
score=int(input('请输入您的python成绩:'))
print(score>60)
print(score>=60)
print(score<60)
print(score<=60)
print(score==100)
print(score!=0)
|
import random
name_list = ['Alise', 'Bob', 'Cindy']
num = len(name_list)
stu_info = []
stu_info_2 = []
# 方法1:stu_info包含num个小列表,对应每个人的姓名和年龄
for i in range(num):
age = random.randint(0, 51)
stu_i = [name_list[i], age]
stu_info.append(stu_i)
print("方法1:")
for i in stu_info:
print(i)
# 方法2:stu_info包含姓名列表和年龄列表
age_list = []
for i in range(num):
age = random.randint(0, 51)
age_list.append(age)
stu_info_2.append(name_list)
stu_info_2.append(age_list)
print("\n方法2:")
for i in range(num):
print([stu_info_2[0][i], stu_info_2[1][i]])
# len(x):返回列表长度
# type(x):返回x的类型
|
# 方法一:
for i in range(1, 11):
for j in range(1, i):
print('*', end = '')
print('*')
print('-' * 20)
# 方法二:
for i in range(1, 11):
a = ''
for j in range(1, i+1):
a += "*"
print(a)
|
# Python中的函数的用法
# 函数,又叫方法,表示一个功能
# print('') input()
# str(1) int('')
# append('') insert(2, '') pop()
# items() pop() get()
# random.randint()
# range()
# 输出3遍Hello
# 输出5遍World
# 输出4遍Hello
# 输出5遍World
# 输出3遍Hello
# 输出3遍World
a = for i in range(3):
print('Hello')
b = for i in range(5):
print('World')
for i in range(4):
print('Hello')
b
a
for i in range(3):
print('World')
|
#Grater number between two numbers
a=30
b=20
c=25
if b<c<a:
print('c the graeter number ')
else:
print('c is not a grater number')
|
#!/usr/bin/env python3
# https://adventofcode.com/2020/day/7
import os
import sys
from collections import defaultdict
with open(os.path.join(sys.path[0], "input.txt"), "r") as file:
lines = [line.rstrip("\n") for line in file]
d = defaultdict(list)
d2 = defaultdict(list)
for line in lines:
color1 = " ".join(line.split()[:2])
chunks = line.split("contain ")[1].split(", ")
for chunk in chunks:
color2 = " ".join(chunk.split()[1:3])
d[color2].append(color1)
q = chunk.split()[0]
if q == "no":
d2[color1].append((color2, 0))
else:
d2[color1].append((color2, int(q)))
def check(color, k):
for char in d[color]:
k.add(char)
check(char, k)
return k
print(len(check("shiny gold", set())))
def count(color):
return 1 + sum(n * count(char) for char, n in d2[color] if n > 0)
print(count("shiny gold") - 1)
|
#!/usr/bin/env python3
# https://adventofcode.com/2020/day/21
import os
import sys
import regex
with open(os.path.join(sys.path[0], "input.txt"), "r") as file:
lines = [line.rstrip("\n") for line in file]
def parse_foods(data):
candidates = {}
ingredients = []
for line in data:
match = regex.search(r'(?:(?P<ingredients>\w+)(?: )?)+\(contains (?:(?P<allergens>\w+)(?:, )?)+\)', line).capturesdict()
ingredients.extend(match['ingredients'])
for allergen in match['allergens']:
if allergen in candidates:
candidates[allergen] &= set(match['ingredients'])
else:
candidates[allergen] = set(match['ingredients'])
return candidates, ingredients
def get_output(data):
candidates, ingredients = parse_foods(data)
found = {}
while candidates:
for allergen, ingredient in list(candidates.items()):
if len(ingredient) == 1:
found[allergen] = min(ingredient)
del candidates[allergen]
else:
candidates[allergen] -= set(found.values())
print(len([ingredient for ingredient in ingredients if ingredient not in found.values()]))
print(','.join([v for k,v in sorted(found.items())]))
get_output(lines)
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
##assumption lets consider the index position as role number of student.
## we will create the three list as math,chem,phy.
## score will be out of 100
#
# In[1]:
math = []
phy = []
chem = []
listof_rollno_reappering_std = []
listof_rollno_failure_std = []
passlist = []
distinction = []
firstclass = []
secondclass = []
N = int(input("please provide the no of studentin the class: "))
for i in range(N):
mathmarks = int(input(f"please provide math marks of roll no {i} student: "))
math.append(mathmarks)
phymarks = int(input(f"please provide phy marks of roll no{i} student: "))
phy.append(phymarks)
chemmarks = int(input(f"please provide chem marks of roll no{i} student: "))
chem.append(chemmarks)
# In[2]:
def result():
N = int(input("please provide the no of studentin the class: "))
for i in range(N):
if (math[i] < 50 and chem[i] < 50) or (math[i]<50 and phy[i]<50) or (chem[i]<50 and phy[i]<50) or(chem[i]<50 and math[i]<50 and phy[i]<50):
print(f"student of roll no{i} is failed!!!")
listof_rollno_failure_std.append(i)
elif (math[i] <50 and chem[i]>50 and phy[i]>50) or (phy[i] <50 and math[i]>50 and chem[i]>50) or (chem[i] <50 and phy[i]>50 and math[i]>50):
print(f"student of roll no {i} can reappear!!!")
listof_rollno_reappering_std.append(i)
else:
print(f"for student of roll no {i} result is PASS")
performance(math[i],phy[i],chem[i])
passlist.append(i)
# In[3]:
def performance( math, phy, chem):
sum = math + phy + chem
percentage = (sum * 100)/300
print(f" percentage of student is {percentage}")
if percentage>80 :
print("/n !!!! Distinction!!!!")
distinction.append(i)
elif 60 <= percentage <=79 :
print("/n !! first class")
firstclass.append(i)
elif 50 <= percentage <=59:
print("/n !! second class")
secondclass.append(i)
# In[4]:
def classperformance():
T_passed_student = len(passlist)
T_failure_student = len(listof_rollno_failure_std) + len(listof_rollno_reappering_std)
T_firstclass = len(firstclass)
T_distinction = len(distinction)
T_secondclass = len(secondclass)
print(f"distinction % is { (T_distinction * 100) /T_passed_student }")
print(f"first class % is {(T_firstclass * 100)/T_passed_student}")
print(f"secondclass class % is {(T_secondclass * 100)/T_passed_student}")
# In[5]:
result()
# In[6]:
classperformance()
# In[ ]:
|
import os
def usr_str():
print("Input a string that has multiple words.")
print("Example: My name is Kyle")
return input("--> ")
def reverse_order(usr_str):
usr_str = usr_str.split(" ")
rev = usr_str[::-1]
joined = " ".join(rev)
return joined
def main():
play = True
while play == True:
usr_str_s = usr_str()
print(reverse_order(usr_str_s))
play_again = input('Do you want to enter another string? "Yes" or "No": ')
if play_again == "yes":
play = True
os.system('clear')
else:
play = False
if __name__ == "__main__":
main()
|
from bs4 import BeautifulSoup
import sys
import os
import requests
from ast import literal_eval
def get_links(url):
r = requests.get(url)
contents = r.content
soup = BeautifulSoup(contents)
links = set()
with open("links_methods.txt", "a") as file:
for link in soup.findAll('a'):
try:
links.add(link['href'])
print link.get_text()
print link.get('href')
print link.get('attr')
print '\n'
#file.write(link['href'] + "\n")
except KeyError:
pass
#file.write(link['href'] + "\n")
#file.write(str(links) + "\n")
#return links
lis = str(list(links))
string = lis.split()
for i in string:
print i
print '\n'
file.write(str(i) + "\n")
def restart_program():
"""Restarts the current program.
Note: this function does not return. Any cleanup action (like
saving data) must be done before calling this function."""
## python = sys.executable
## os.execl(python, python, * sys.argv)
url = raw_input('Enter url starting without http:// - ')
url = "http://" + url
print get_links(url)
if __name__ == "__main__":
while 1==1:
url = raw_input('Enter url starting without http:// - ')
url = "http://" + url
print get_links(url)
answer = raw_input("Do you want to restart this program ? ")
if answer.lower().strip() in "y yes".split():
restart_program()
if answer.lower().strip() in "n no".split():
sys.exit()
## url = raw_input('Enter url: ')
## print get_links(url)
|
# Python_Page_Spider_Web_Crawler_Tutorial
# from https://www.youtube.com/watch?v=SFas42HBtMg&list=PLa1r6wjZwq-Bc6FFb9roP7AZgzDzIeI8D&index=3
# Spider algorithm.
# You need to EXECUTE the file in Shell, e.g. execfile("nytimes/scrape.py")
# First open cmd. Then cd C:\Users\Joh\Documents\Python Scripts\Web Crawler Projects\nytimes.
# Then enter Python Scrape.py
import urlparse
import urllib
#import urllib.request for Python3?
from bs4 import BeautifulSoup
import csv
import requests
import re
with open ('links.csv') as f:
f_csv = csv.reader(f)
#headers = next(f_csv)
for headers in f_csv:
#print headers
urls = headers
urls_name = urls
#print type(urls)
urls = "http://www." + str(headers[0])
urls = urls.split()
urls_name = str(urls_name[0])
urls_name = urls_name.replace("/", "")
visited = [urls]
#print urls
#print type(urls)
#print id(urls)
#print '\n'
while len(urls) >0:
try:
htmltext = urllib.urlopen(urls[0]).read()
#r = requests.get(urls[])
#urls.pop(0)
except:
print urls[0]
soup = BeautifulSoup(htmltext)
regex = '<title>(.+?)</title>'
pattern = re.compile(regex)
titles = re.findall(pattern,htmltext)
#urls.pop(0)
## print headers
## print "STARTS HERE: \n"
## print "\n" + "\n"
## print soup.findAll('a', href=True)
##
## print "\n\n\n"
#items = soup.findAll('a', href=True)
textall = soup.get_text()
print headers
def get_file(self, url, default='index.html'):
'Create usable local filename from URL'
parsed = urlparse.urlparse(headers)
host = parsed.netloc.split('@')[-1].split(':')[0]
filepath = '%s%s' % (host, parsed.path)
if not os.path.splitext(parsed.path)[1]:
filepath = os.path.join(filepath, default)
linkdir = os.path.dirname(filepath)
if not os.path.isdir(linkdir):
if os.path.exists(linkdir):
os.unlink(linkdir)
os.makedirs(linkdir)
return headers, filepath
#items2 = "STARTS HERE:\n\n" + str(items)
saveFile = open (str(urls_name)+'.txt','a')
saveFile.write(str(urls)+ '\n')
#saveFile.write(items2)
#saveFile.write(str(textall))
saveFile.write(str(titles)+ '\n')
saveFile.write(str(textall)+ '\n')
saveFile.close()
#print items
print textall
'''
for tag in soup.findAll('a', href=True):
# print tag
# print tag['href'] # is you just want to print href
tag['href'] = urlparse.urljoin(url,tag['href'])
#print tag['href']
if url in tag['href'] and tag['href'] not in visited:
urls.append(tag['href'])
visited.append(tag['href']) # historical record, whereas above line is temporary stack or queue.
print visited
'''
|
def insertion_sort(arr):
for i in range(1, len(arr)):
t = arr[i]
j = i - 1
while (j >= 0 and t < arr[j]):
arr[j + 1] = arr[j]
alg_count[0] += 1
j = j - 1
arr[j + 1] = t
alg_count[1] += 1
import timeit
a = timeit.default_timer()
import random
DIM = 20
arr = [random.randint(0, 100) for i in range(DIM)]
print(arr)
alg_count = [0, 0]
insertion_sort(arr)
print(arr)
print("Сравнений: ", alg_count[1])
print("Перестановок: ", alg_count[0])
print(timeit.default_timer()-a)
|
# -*- coding: utf-8 -*-
'''
Control Flow
'''
def main():
# Variable
x = 21
# if, elif and else Statement
if x < 0:
print "x is negative"
elif x % 2:
print "x is positive and odd"
else:
print "x is even and non-negative"
# For loop
words = ['cat', 'window', 'defenestrate']
for w in words:
print w, len(w)
# break and continue Statements, and else Clauses
# below code searches for prime numbers
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print n, 'equals', x, '*', n/x
break
else:
# loop fell through without finding a factor
print n, 'is a prime number'
# Access every 3rd element in a list using while loop
i = 0
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
while i < len(a):
print a[i]
i = i + 3
# pass Statements
while True:
pass # Busy-wait for keyboard interrupt (Ctrl+C)
# Practice excercise
def excercise():
print 'Write a program to validate given person\'s age is 18 or not. If yes, print DOB';
if __name__ == '__main__':
main();
|
# -*- coding: utf-8 -*-
'''
Set
It is an unordered collection with no duplicate elements.
Basic uses include membership testing and eliminating duplicate entries.
Set object also support mathematical operations like union, intersection, difference, and symmetric difference.
Curly braces or the set() function can be used to create sets
Note:
To create an empty set you have to use set(), not {}.
'''
def main():
# Sets
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
fruit =set(basket) # create a set without duplicates
print fruit # fruit does not have duplicate values
# fast membership testing
print 'Does orange exists in fruit?','orange' in fruit
# Demonstrate set operations on unique letters from two words
a = set('abracadabra')
b = set('alacazam')
print 'Unique letters in \'abracadabra\' -->', a
print 'Unique letters in \'alacazam\' -->', b
# letters in a but not in b
print 'Letters in a but not in b -->', a - b
# letters in either a or b
print 'Letters in either a or b -->', a | b
# letters in both a and b
print 'Letters in both a and b -->', a & b
# letters in a or b but not both
print 'Letters in a or b but not both -->', a ^ b
# set comprehensions
'''
Similarly to list comprehensions, set comprehensions are also supported.
'''
print {x for x in 'abracadabra' if x not in 'abc'}
print 'Python'
def excercise():
print 'Write a programm to :?'
if __name__ == '__main__':
main();
excercise();
|
# -*- coding: utf-8 -*-
'''
Assignment Operators
'''
def main():
# Integers
a = 21
b = 10
c = 0
# Assignment Operators
c = a + b
print "Value of c is ", c
c += a
print "Value of c is ", c
c *= a
print "Value of c is ", c
c /= a
print "Value of c is ", c
c = 2
c %= a
print "Value of c is ", c
c **= a
print "Value of c is ", c
c //= a
print "Value of c is ", c
# Practice excercise
def excercise():
print 'Write a program to Hmmmmm!!';
if __name__ == '__main__':
main();
|
"""text feature extraction.
feature: word presence captured by bag of words."
1. filter stopwords.
2. include significant bigrams using chi_sq score function.
"""
import nltk
from nltk.corpus import stopwords
from nltk.collocations import BigramCollocationFinder
from nltk.metrics import BigramAssocMeasures
def bag_of_words(words, stopfile='english', score_fn=BigramAssocMeasures.chi_sq,
n=200):
remaining_words = set(words) - set(stopwords.words(stopfile))
return dict([(word, True) for word in (remaining_words)])
"""
bigram_finder = BigramCollocationFinder.from_words(remaining_words)
bigrams = bigram_finder.nbest(score_fn, n)
return dict([(word, True) for word in (remaining_words | set(bigrams))])
"""
|
# 1
a = int(input())
b = int(input())
c = int(input())
print(a + b + c)
# Tkinter2
b = int(input())
h = int(input())
print(b * h / 2)
# 3
n = int(input())
k = int(input())
print(k // n)
print(k % n)
# 4
# делением на 60 узнаем количество часов для n минут.
# делением с остатком на 24 узнаем количество часов с начала новых суток
n = int(input())
print(n // 60 % 24, n % 60)
# 5
n = input()
print("Hello, " + n + "!")
# 6
n = int(input())
print("The next number for the number " + str(n) + " is " + str(n + 1) + ".")
print("The previous number for the number " + str(n) + " is " + str(n - 1) + ".")
# 7
# прибавил + 1 к каждому классу
a = int(input())
b = int(input())
c = int(input())
print((a + 1) // 2 + (b + 1) // 2 + (c + 1) // 2)
# 8
# посчитал количество отрезков на картинке
a = int(input())
b = int(input())
l = int(input())
N = int(input())
print((l + N * a + (N - 1) * b) * 2 - a) |
def Sort(num):#升序
MergeSort(num,0,len(num)-1)
def Merge(num,left,mid,right):
tmp = []
i = left
j = mid+1
while i<=mid and j<=right:
if num[i]>num[j]:
tmp.append(num[j])
j+=1
else:
tmp.append(num[i])
i+=1
while i<=mid:
tmp.append(num[i])
i += 1
while j<=right:
tmp.append(num[j])
j+=1
for i in range(left,right+1):
num[i]= tmp[i-left]
def MergeSort(num,left,right): # 将num数组中,left到right这一段归并排序,结果储存在num中
if left<right:
mid = (left+right)//2
MergeSort(num,left,mid)
MergeSort(num,mid+1,right)
Merge(num,left,mid,right)
num = [8,4,5,7,1,3,6,2]
Sort(num)
print(num) |
def sort_by_ratio(item):
return item[1]
def Knapsack(w,v,c):
ratio = []
r = [0 for i in range(len(w))]
for i in range(len(w)):
ratio.append((i,v[i]/w[i])) # 比重越大,越值得放入背包
ratio.sort(key=sort_by_ratio,reverse=True)
print("根据价值与重量比值降序排列",ratio)
tmp_c = c
total = 0
for i in range(len(w)):
if w[ratio[i][0]]<tmp_c:
r[ratio[i][0]] =1
tmp_c = tmp_c - w[ratio[i][0]]
total += v[ratio[i][0]]
elif tmp_c > 0:
r[ratio[i][0]] = tmp_c/w[ratio[i][0]]
total += v[ratio[i][0]] * r[ratio[i][0]]
break
print("解向量",r)
print("最大总价值",total)
if __name__ == '__main__':
w = [20,30,10]
v = [60,120,50]
r = Knapsack(w,v,50)
|
def put_pivot(num,left,right):
pivot = num[left]
i = left
j = right
while i<j:
while num[j]>=pivot and i<j:
j-=1
num[i]=num[j]
while num[i]<=pivot and i<j:
i+=1
num[j]=num[i]
num[i] = pivot
return i
def divide_conquer(num,left,right):# 对left和right之间的段落进行排序,结果仍存放在num中
if left<right: # 边界限制
i = put_pivot(num,left,right)
divide_conquer(num,left,i-1)
divide_conquer(num,i+1,right)
def QuickSort(num):
divide_conquer(num,0,len(num)-1)
num = [49,38,65,97,76,13,27,49]
QuickSort(num)
print(num) |
def binsearch(num,left,right,target):
if left>right: # 边界限制
return
mid = (left+right)//2
if num[mid] == target:
return mid
if num[mid]>target:
r = binsearch(num,left,mid-1,target)
else:
r = binsearch(num,mid+1,right,target)
return r if r else -1 # 可能找不到
r = binsearch([5],0,0,21)
print(r) |
from collections import defaultdict
def simple_cycles(G):
# Yield every elementary cycle in python G exactly once
def unblock(thisnode, blocked, B):
# to get unique values
stack = set([thisnode])
# while stack is not empty
while stack:
# get top element of stack
node = stack.pop()
if node in blocked:
blocked.remove(node)
stack.update(B[node])
B[node].clear()
# A duplicate copy of the graph
# nbrs = neighbours
G = {v: set(nbrs) for (v,nbrs) in G.items()}
# using function to get all strongly connected components of the graph
sccs = strongly_connected_components(G)
#print("sccs = ",sccs)
# using strongly connected components in the graph to find all unique cycles
while sccs:
# get the group of strongly connected vertices
scc = sccs.pop()
#print(scc)
startnode = scc.pop()
#print(startnode)
path = [startnode]
# declaring blocked and closed sets
blocked = set()
closed = set()
blocked.add(startnode)
# declaring B as a default dictionary
B = defaultdict(set)
# creating a stack containing start node and all its neighbours
stack = [(startnode,list(G[startnode])) ]
#print("stack = ",stack)
while stack:
#print("start node = ",startnode)
#print("stack_start = ", stack)
thisnode, nbrs = stack[-1]
#print(thisnode, nbrs)
# if the current start node has neighbours
if nbrs:
# going to neighbour node
nextnode = nbrs.pop()
#print("popped = ",nextnode)
# if the next node is start node itself, we found a cycle
if nextnode == startnode:
#print("cycle found = ",path[:])
# get the whole path of cycle traversed
yield path[:]
# closed will contain all the cycle paths already discovered
closed.update(path)
elif nextnode not in blocked:
# add next node to path
path.append(nextnode)
#print("path = ",path)
# now update stack with this next node and its neighbours
stack.append( (nextnode,list(G[nextnode])) )
#print("stack-2 = ",stack)
# remove nextnode from closed nodes list
#print("next node = ", nextnode)
closed.discard(nextnode)
#print("closed = ",closed)
# add it to blocked nodes list
blocked.add(nextnode)
#print("blocked = ",blocked)
continue
# if the node has no neighbours
if not nbrs:
# if the nodes is closed, then unblock it
if thisnode in closed:
unblock(thisnode,blocked,B)
else:
for nbr in G[thisnode]:
if thisnode not in B[nbr]:
B[nbr].add(thisnode)
stack.pop()
path.pop()
remove_node(G, startnode)
H = subgraph(G, set(scc))
sccs.extend(strongly_connected_components(H))
# Tarjan's Method for SCC
def strongly_connected_components(graph):
index_counter, stack, lowlink, index, result = [0], [], {}, {}, []
# Nested functions
def strong_connect(node):
index[node] = index_counter[0]
lowlink[node] = index_counter[0]
index_counter[0] += 1
stack.append(node)
successors = graph[node]
for successor in successors:
if successor not in index:
strong_connect(successor)
lowlink[node] = min(lowlink[node], lowlink[successor])
elif successor in stack:
lowlink[node] = min(lowlink[node], index[successor])
if lowlink[node] == index[node]:
connected_component = []
while True:
successor = stack.pop()
connected_component.append(successor)
if successor == node: break
result.append(connected_component[:])
for node in graph:
if node not in index:
strong_connect(node)
return result
# Both below two fns expect values of G to be sets
def remove_node(graph, target):
del graph[target]
for i in graph.values():
i.discard(target)
# Get the subgraph of G induced by set vertices
def subgraph(graph, vertices):
return {v: graph[v] & vertices for v in vertices}
def print_cycles_in_graph(graph):
print(graph)
no_cycles = 0
s = ""
cycles = simple_cycles(graph)
for c in cycles:
for i in c:
s+= "T"+str(i+1)+" "
print("Conflict - {}".format(no_cycles+1)+" : "+s)
no_cycles+=1
# reset string
s = ""
|
import matplotlib.pyplot as plt
n = int(input("Enter generation number\n"))
def func(p, w11, w12, w22):
a = [p]
b = [0]
c = [(1-p)**2]
d = [2*p*(1-p)]
for i in range(1, n):
p += p*(1-p)*(p*(w11-w12)-(1-p)*(w22-w12))/(p**2*w11+2*p*(1-p)*w12+(1-p)**2*w22)
a.append(p)
b.append(i)
plt.plot(b, a)
plt.xlabel('No. of Generations')
plt.ylabel('Frequency of p')
plt.show()
func(0.4, 1, 0.5, 0.8) |
class Student:
def __init__(self,first_name,second_name,age,):
self.first_name = first_name
self.second_name = second_name
self.age = age
def full_name(self):
name = self.first_name + self.second_name
return name
def year_of_birth(self):
return 2019 - self.age
def initials(self):
initials = self.first_name[0] + self.second_name[0]
return initials
|
class Multionationale:
def __init__(self,nom,pays):
self.__nom = nom
self.__pays = pays
self.__filiale = []
def AjouterFiliale(self,filiale):
self.__filiale.append(filiale)
def Afficher(self):
print(f"- La multinationale {self.__nom} est composée de {len(self.__filiale)} filiales. Son pays d'origine est : {self.__pays}.")
dateplusvielle = 999999999999999999999999999999999
counter = 0
numerofiliale = 0
nombretotal = 0
for i in self.__filiale:
datefiliale = i.gettdate()
nombretotal = nombretotal + (self.__filiale[counter]).gettnombresalarie()
if datefiliale < dateplusvielle :
dateplusvielle = datefiliale
numerofiliale = counter
counter = counter + 1
filialelaplusvielle = (self.__filiale[numerofiliale]).gettnom()
nombredemploye = (self.__filiale[numerofiliale]).gettnombresalarie()
print(f"- La filiale la plus ancienne de cette multinationale est {filialelaplusvielle}: . Elle est composée de {nombredemploye} salariés.")
print(f"- {self.__nom} est composée de {nombretotal} salariés :")
for f in self.__filiale:
f.Afficher()
|
"""
MoveZeroes to the end
"""
def moveZeros(nums):
if len(nums) == 1:
return nums
slow = 0
fast = 0
while fast < len(nums):
if nums[fast] != 0:
nums[fast], nums[slow] = nums[slow], nums[fast]
if nums[slow] != 0:
slow += 1
fast += 1
return nums
nums = [0, 0, 1, 3, 12]
print(moveZeros(nums))
|
#
# Binary trees are already defined with this interface:
# class Tree(object):
# def __init__(self, x):
# self.value = x
# self.left = None
# self.right = None
def inorderRec(node, lst):
if node.left:
inorderRec(node.left, lst)
if node is not None:
lst.append(node.value)
if node.right:
inorderRec(node.right, lst)
return lst
def kthSmallestInBST(t, k):
if t is None or k < 1:
return 0
# inorder traversal
lst = inorderRec(t, [])
return lst[k - 1]
|
def search(self, nums, target):
def rotate_idx(l,r,nums):
if nums[l]<nums[r]:
return 0
while l<=r:
mid = l+(r-l)//2
if nums[mid]>nums[mid+1]:
return mid+1
else:
if nums[mid]>=nums[l]:
l = mid+1
else:
r = mid-1
def binary_search(left,right,nums):
while left<=right:
mid =left+(right-left)//2
if nums[mid]<target:
left = mid+1
elif nums[mid]>target:
right=mid-1
else:
return mid
return -1
if not nums:
return -1
if len(nums)==1:
if nums[0]==target:
return 0
else:
return -1
left,right =0,len(nums)-1
idx = rotate_idx(left,right,nums)
if idx==0:
return binary_search(left,right,nums)
if nums[idx] == target:
return idx
if target<nums[0]:
return binary_search(idx,right,nums)
else:
return binary_search(left,idx,nums)
return -1
|
def permute(nums):
res = []
path = []
used = [False] * len(nums)
dfs(nums, res, path, used)
return res
def dfs(nums, res, path, used):
if len(path) == len(nums):
res.append(path[:])
return
for i in range(len(nums)):
if not used[i]:
used[i] = True
path.append(nums[i])
dfs(nums, res, path, used)
path.pop()
used[i] = False
nums = [1, 2, 3]
print(permute(nums))
|
"""
Find the duplicate number:
using 3 methods
1) brute force using sort
2) set
3) cycle detection algo -tortoise and hare
"""
def findDuplicate(nums):
# brute force and sort
# Time: O(nlogn) and space: o(1)
nums.sort()
prev = nums[0]
for i in range(1, len(nums)):
if nums[i] == prev:
return nums[i]
prev = nums[i]
return None
def findDuplicate_set(nums):
# with set and time:o(n)
# and space:O(n)
nums_set = set()
for i in range(0, len(nums)):
if nums[i] in nums_set:
return nums[i]
nums_set.add(nums[i])
def findDuplicate_cycle(nums):
# Using floyd's Hare and Tortoise
t = nums[0]
h = nums[0]
while True:
t = nums[t]
h = nums[nums[h]]
if t == h:
break
t = nums[0]
while t != h:
t = nums[t]
h = nums[h]
return h
print(findDuplicate([1, 3, 4, 2, 2]))
print(findDuplicate_set([1, 3, 4, 2, 2]))
print(findDuplicate_cycle([1, 3, 4, 2, 2]))
|
class Node(object):
def __init__(self, value):
self.data = value
self.next = None
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def AddDigit(self, val):
node = Node(val)
if self.head is None:
self.head = node
else:
self.tail.next = node
self.tail = node
def PrintList(self):
start = self.head
temp = []
while start is not None:
temp.append(str(start.data))
start = start.next
return temp
def reverseList(self):
head = self.head
currNode, prevNode, nextNode = None, None, None
while head:
currNode = head
nextNode = head.next
head.next = prevNode
prevNode = currNode
head = nextNode
return prevNode
def AddTwoLists(lst1, lst2):
pass
def main():
lst1 = LinkedList()
lst1.AddDigit(7)
lst1.AddDigit(2)
lst1.AddDigit(4)
lst1.AddDigit(3)
print(lst1.PrintList())
lst2 = LinkedList()
lst2.AddDigit(5)
lst2.AddDigit(6)
lst2.AddDigit(4)
print(lst2.PrintList())
revLst1 = lst1.reverseList()
revLst2 = lst2.reverseList()
main()
|
# def reverseWords(s):
# s = s.split()
# return " ".join(reversed(s))
# using deque and two pointer
from collections import deque
def reverseWords(s):
if len(s) < 1:
return ""
left = 0
right = len(s) - 1
while left <= right and s[left] == " ":
left += 1
while left <= right and s[right] == " ":
right -= 1
dq = deque()
word = []
while left <= right:
if s[left] == " " and word:
dq.appendleft("".join(word))
word = []
elif s[left] != " ":
word.append(s[left])
left += 1
dq.appendleft("".join(word))
return " ".join(dq)
# s = "a good example"
s = " hello world! "
print(reverseWords(s))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.