text
stringlengths 37
1.41M
|
---|
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.previous = None
class DLinkedList:
def __init__(self):
self.first_node = None
self.last_node = None
self.count = 0
def add(self, index, data):
existing_node = getNode(self, index)
new_node = Node(data)
prev_node = existing_node.previous
prev_node.next = new_node
new_node.next = existing_node
new_node.previous = prev_node
self.count = self.count + 1
def addFirst(self, data):
new_node = Node(data)
if self.count==0:
self.first_node = new_node
self.last_node = new_node
else:
self.first_node.previous = new_node
new_node.previous = self.last_node
new_node.next = self.first_node
self.first_node = new_node
self.count = self.count + 1
def addLast(self, data):
new_node = Node(data);
if (node_count==0):
this.first_node = new_node;
this.last_node = new_node;
new_node.next = new_node;
new_node.previous = new_node;
else:
self.last_node.next = new_node
new_node.next = self.first_node
new_node.previous = self.last_node
self.last_node = new_node
self.first_node.previous = new_node
self.count = self.count + 1
def delete(self, index):
existing_node = getNode(self, index)
prev_node = existing_node.previous
next_node = existing_node.next
prev_node.next = next_node
next_node.previous = prev_node
if (index==0):
this.first_node = next_node
elif (index==(node_count-1)):
this.last_node = prev_node
self.count = self.count - 1
def size(self):
return self.count
def clear(self):
this.first_node = None
this.last_node = None
self.count = 0
def get(self, index):
existing_node = getNode(self, index)
return selected_node.data;
def getNode(self, index):
selected_node = self.first_node;
for i in range(index):
selected_node = selected_node.next
return selected_node
|
# Numbers, Lists, Tuples, Sets
# numbers that look like strings
# vars that look like numbers
# num_1 = '100'
# num_2 = '200' # this is a string lol
# print(num_1 + num_2)
# returns: 100200
# ~CASTING
# to turn them into integers
# num_1 = int(num_1)
<< << << < HEAD
# num_2 = int(num_2) # this is a function to create an interger
== == == =
# num_2 = int(num_2) # this is a function o create an integer
>>>>>> > facc01caaaefed076bbc4e48ad495727b323ab1b
# print(num_1 + num_2)
# Python Tutorial for Beginners 4: Lists, Tuples, and Sets
# ~LISTS[]
# work with a list of values
# courses = ['Python', 'C#', 'Ruby', 'GIT']
# print(courses[2])
# Negative index- -1 will always be the last item.
# Index error- no item
# print(courses[-1])
# ~SLICING
# we want all the values starting from the beginning
# and up to but not including eg:
# print(courses[0:2]) # should print out python and C#
# you can leave out the 0- it assumes you start from the
# beginning
# if nothing is put next to the : , it assumes it wants to go to
# the end of the list
# ~APPEND
# Adds to the list, puts it at the end
# courses.append('Atom')
# print(courses)
# ['Python', 'C#', 'Ruby', 'GIT', 'Atom']
# ~INSERT
# Insert adds it to a specific location
# Takes two arguments (the index you want to insert it)
# (location : value) eg:
# print(courses)
# courses.insert(1, 'Atom')
# print(courses)
# ['Python', 'C#', 'Ruby', 'GIT']
# ['Python', 'Atom', 'C#', 'Ruby', 'GIT']
# ~EXTEND
# for multiple values we want to add to our list
# courses_2 = ['cooking', 'karate']
# courses.insert(0, courses_2)
# print(courses)
# [['cooking', 'karate'], 'Python', 'C#', 'Ruby', 'GIT']
# INSERT in this case inserts the whole list
# instead of individual values inside the list
# So instead use INSERT
# courses.insert(courses_2)
# print(courses)
# ['Python', 'C#', 'Ruby', 'GIT', 'cooking', 'karate']
# ~REMOVE
# removing values from our list
# courses.remove('C#')
# print(courses)
# courses = ['Python', 'C#', 'Ruby', 'GIT']
# or you can use ~POP
# courses.pop()
# removes the last item on the list
# print(courses)
# ['Python', 'C#', 'Ruby'](removed GIT)
# pop also prints out the value it removed
# deleted = courses.pop()
# print(deleted) # GIT
# print(courses) # ['Python', 'C#', 'Ruby']
# courses = ['Python', 'C#', 'Ruby', 'GIT']
# ~REVERSE
# courses.reverse()
# ~SORTING
# Sorts alphabetically
# courses.sort()
# print(courses)
# ['C#', 'GIT', 'Python', 'Ruby']
# Also sorts numbers in ascending order
# nums = [4, 5, 8, 4, 22, 0] # [0, 4, 4, 5, 8, 22]
# nums.sort()
# print(nums)
# Descending Order
# courses.sort(reverse=True)
# nums.sort(reverse=True)
# print(nums)
# print(courses)
# [22, 8, 5, 4, 4, 0]
# ['Ruby', 'Python', 'GIT', 'C#']
# These alters the originals
# SORTED function (different to the sort method)
# sorted(nums)
# print(nums)
# list is not sorted it's the same
# this is beacause the ~sorted function does not sort list in place
# returns a sorted version of the list
# [4, 5, 8, 4, 22, 0]
# sorted_nums = sorted(nums)
# print(sorted_nums)
# [0, 4, 4, 5, 8, 22] - sorted
# this does not alter the originals
# ~MIN AND MAX/SUM
# print(min(nums)) # 0
# print(max(nums)) # 22
# print(sum(nums)) # 43
# Finding the ~INDEX VALUE in our list
# courses = ['Python', 'C#', 'Ruby', 'GIT']
# print(courses.index('GIT')) # index 2
# To check if a value is even in our list and to check
# if a value is true or false: "IN FUNCTION"
# print('Art' in courses) # returns false because 'Art' is not on the list
# ~FOR LOOP
# for item in courses:
# print(item) # we want to print out that item
# Creating a loop that goes through each value of the list
# Each loop through this item variable will be
# equal to the next item in the list
# The indentation is to say the code is executed from within the for loop
# "item" is just a var, it can be changed
# ~ENUMERATE function
# for index, item in enumerate(courses):
# print(index, item) # returns:
# 0 Python
# 1 C#
# 2 Ruby
# 3 GIT
# if we do not want to start from 0
# we can pass in a start value to "enumerate" function
# for index, item in enumerate(courses, start=1):
# print(index, item) # returns starting value as 1
# ~JOIN
# Turning lists into str's separated by a values
courses = ['Python', 'C#', 'Ruby', 'GIT']
# courses_str = ' - '.join(courses)
# print(courses_str)
# Returns {Python -C# -Ruby -GIT}
# ~SPLIT
# new_list = courses_str.split(' - ') # split up the values on this space,
# print(new_list)
# Returns ['Python', 'C#', 'Ruby', 'GIT']
# TUPLES() & SETS{}
# similar to lists but can't modify them
# mutable eg: "lists" immutable eg: "turps"
# immutable- not many methods to use, can loop, access values.
# can't be modified
# tuple1 = ('Hugs', 'Food', 'Stuff')
# tuple2 = tuple1
# print(type(tuple1))
# print(tuple1)
# print(tuple2)
# if we were to try modify it:
# tuple1[1] = 'Cake' -it would return
# TypeError: 'tuple' object does not support item assignment
# pro tip- ctrl + / = comment out code fast
# ~SETS
# do not care about order and always change {} eg:
# set_list = {'home', 'food', 'sleep}
# print(set_list)
# results in:{'food', 'home', 'sleep'}
# main uses for a test is to test if a value is part of a set
# and to remove duplicate values eg:
# set_list = {'home', 'food', 'food', 'sleep'}
# print(set_list)
# returns with {'food', 'home', 'sleep'}
# Tests if a value is part of a set "membership test"
# Membership tests can be done with lists + tuples too
# Sets are optimized for this
# print(set_list)
# within print statement- eg
# print('home' in set_list) # returns True
# ~INTERSECTION
# checks similarities in both sets eg:
# set_list = {'home', 'food', 'food', 'sleep'}
# inter_list = {'dogs', 'food', 'cats', 'sleep'}
# print(set_list.intersection(inter_list))
# returns: {'food', 'sleep'} as these are in the same set
# ~DIFFERENCE
# checks differences in sets eg:
# set_list = {'home', 'food', 'food', 'sleep'}
# inter_list = {'dogs', 'food', 'cats', 'sleep'}
# print(set_list.difference(inter_list))
# # returns: {'home'}
# ~UNION method
# print out all sets, conjoined together eg:
# set_list = {'home', 'food', 'food', 'sleep'}
# inter_list = {'dogs', 'food', 'cats', 'sleep'}
# print(set_list.union(inter_list))
# returns {'food', 'sleep', 'dogs', 'cats', 'home'}
# # Empty Lists
# empty_list = []
# empty_list = list()
# # Empty Tuples
# empty_tuple = ()
# empty_tuple = tuple()
# # Empty Sets
# empty_set = {} # This isn't right! It's not an empty set its a dictionary
# empty_set = set() # Right way to do it
|
import logging
import threading
import time
def thread_function(name):
print("Thread {}: starting".format(name))
time.sleep(2)
print("Thread {}: finishing".format(name))
# main
print("Main : before creating thread")
x = threading.Thread(target=thread_function, args=(1, ), daemon=True)
# x = threading.Thread(target=thread_function, args=(1, ), daemon=False)
print("Main : before running thread")
x.start()
print("Main : wait for the thread to finish")
print("Main : all done")
# since x is daemon thread, program ends just after main is over, not waiting for the thread to complete
|
# 10. Write a Python program to reverse the digits of an integer.
# Input : 234
# Input : -234
# Output: 432
# Output : -432
def reverseDigits(num):
negFlag = False
if(num < 0):
negFlag = True
num *= -1
place = 10
result = 0
while num > 0:
temp = num % 10
result = result * place + temp
num //= 10
if(negFlag):
result *= -1
return result
num = int(input("Enter a number: "))
result = reverseDigits(num)
print(result)
|
def bubble_sort(lst):
length = len(lst)
print(length)
for i in range(length):
for j in range(length - i - 1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
print(lst)
return lst
lst = [124, 152, 235, -4587, 456, 357, 85, -45, 3467, 90, -5, 26, 78, 32, 7347, 345]
# lst = [3, 5, 6, 3, 2, 7, 1]
print("\n\nAfter Sorting: ", bubble_sort(lst))
|
import re
def validate(input):
up = r"[A-Z]+"
lo = r"[a-z]+"
num = r"\d+"
spe = r"[#$@]+"
min_len = 6
max_len = 12
fails = []
val = True
if len(input) < min_len or len(input) > max_len:
fails.append("Password should of length 6 to 12")
val = False
pattern = re.compile(up)
match = re.search(pattern, input)
if match is None:
fails.append("atleast 1 uppercase required")
val = False
pattern = re.compile(lo)
match = re.search(pattern, input)
if match is None:
fails.append("atleast 1 lowercase required")
val = False
pattern = re.compile(num)
match = re.search(pattern, input)
if match is None:
fails.append("atleast 1 number required")
val = False
pattern = re.compile(spe)
match = re.search(pattern, input)
if match is None:
fails.append("atleast 1 special symbol in (@,#,$) required")
val = False
for fail in fails:
print(fail)
return val
# Driver code
_input = input("Enter password: ")
while not validate(_input):
print("Keep a better password.")
_input = input("Enter password: ")
else:
print("Successful")
|
def create_matrix():
rows = int(input("Enter the number of rows for matrix: "))
columns = int(input("Enter the number of columns for matrix: "))
matrix = get_input(rows, columns)
return matrix
def get_input(rows, columns):
matrix = []
print("Enter the matrix values: ")
for i in range(rows):
temp_row = []
for j in range(columns):
temp_row.append(int(input()))
matrix.append(temp_row)
return matrix
def multiply(m1, m2):
result = []
for i in range(len(m1)):
temp_row = []
for j in range(len(m2[0])):
temp_row.append(0)
result.append(temp_row)
for i in range(len(m1)):
for j in range(len(m2[0])):
for k in range(len(m2)):
result[i][j] += m1[i][k] * m2[k][j]
return result
def print_matrix(matrix):
print("-------------------------")
for i in range(len(matrix)):
for j in range(len(matrix[0])):
print(matrix[i][j], end=" ")
print()
print("-------------------------")
# main
matrix_one = create_matrix()
matrix_two = create_matrix()
print_matrix(matrix_one)
print_matrix(matrix_two)
if len(matrix_one[0]) == len(matrix_two):
print_matrix(multiply(matrix_one, matrix_two))
else:
print("Sorry, multiplication of these two matrices is not possible.")
|
from edit_dist import distance
from random import choice
def find_match(source_word):
"""Finds the best match for a source word"""
min_dist = 100
# min_dist = len(source_word) * 2
optimal_words = []
target_file = open('common_words.txt', 'r')
# FIXME: Runtime of this is O(n^2). Can we improve this?
for line in target_file:
target_word = line.rstrip()
if distance(source_word, target_word) == min_dist:
# Add this word to the list
optimal_words.append(target_word)
if distance(source_word, target_word) < min_dist:
min_dist = distance(source_word, target_word)
# re-initialize the list, with only this word as a possible correction
optimal_words = [target_word]
return choice(optimal_words)
def spellcheck_file():
"""Corrects misspellings in the source file"""
source_file = open('misspellings.txt', 'r')
# iterate thru source & target words
for line in source_file:
source_word = line.rstrip()
print find_match(source_word)
if __name__ == '__main__':
spellcheck_file()
|
# importing the modules needed for all questions
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# Question N.1
s=np.random.rand(1000,2)
#Question N.2
#Scatter plot
x = s[:,0]
y = s[:,1]
plt.scatter(x,y)
plt.title("Scatter plot between $X$ and $Y$")
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.show()
#change colour to green
plt.scatter(x, y, c="green")
plt.title("Scatter plot in green colour")
plt.xlabel("$X$ axis")
plt.ylabel("$Y$ axis")
plt.show()
#change size to very small and colour to red
plt.scatter(x, y, c='red', s=10)
plt.title("Small size scatter plots")
plt.xlabel("$X axis$")
plt.ylabel("$Y axis$")
plt.show()
#now we add a legend and we change the shape and the edgecolours of the points on the scatter plot, while changing more factors such as colour and size
plt.scatter(x, y, c='purple', s=45, label='random x and y coordinates', marker='^', edgecolors="b")
plt.title("Scatter plot")
plt.xlabel("$X axis$")
plt.ylabel("$Y axis$")
plt.legend()
plt.show()
#Line plot with more variations
x1=s[:5,0]
y1=s[:5,1]
y2=s[5:10,1]
x2=s[5:10,0]
plt.plot(x1,y1, c="purple", label="x1 to y1", linestyle="dashed", linewidth=7)
plt.scatter(x2,y2, c="green", label="x2 to y2")
plt.title("Line plot example")
plt.xlabel("$X$ axis")
plt.ylabel("$Y$ axis")
plt.xticks([0,0.5,1])
plt.yticks([0,0.5,1])
plt.legend()
plt.show()
|
from itertools import permutations
num = [8,9,10,5]
op = ['+','-','*','/','b-','b/']
opt = ('+', '-', '*')
print(opt[0])
num_all = list(permutations(num))
op_all = list(permutations(op,3))
print(num_all)
print(op_all)
all = []
for num in num_all:
num = list(num)
for op in op_all:
num.insert(1,op[0])
num.insert(3,op[1])
num.insert(5,op[2])
all.append(num)
print(num)
num.remove(op[0])
num.remove(op[1])
num.remove(op[2])
# num[1:1] = op[0]
# num[3:3] = op[1]
# num[5:5] = op[2]
# # for i in range(1,6,2):
# # num[i:i] = op[0]
# # # count += 1
|
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
#x = mu + sigma * np.random.randn(10000)
# the histogram of the data
plt.axis([amin(x),amax(x), amin(x),amax(x)])
plt.plot(x,x, 'r-')
plt.show()
|
from math import ceil,sqrt;
def prime_generator(needed, primes):
def is_prime(num):
'''can check if a number is prime up to 1000'''
sqrt_num = ceil(sqrt(num));
for p in (prime for prime in primes if prime <= sqrt_num):
if num%p == 0:
return False;
primes.append(num);
return True;
n = 2;
count = 1;
yield n;
n += 1;
while count < needed:
#print(n);
if is_prime(n):
#print("yielding", n);
yield n;
count += 1;
n += 2;
def prime_sum(first_n):
primes = prime_generator(first_n, [2]);
return sum(prime for prime in primes);
if __name__ == '__main__':
print(prime_sum(1000));
|
import sys
def fizz_buzz(fizz_mod, buzz_mod, count):
out = [];
for num in range(1,count + 1):
if num%fizz_mod == 0 and num%buzz_mod == 0:
out.append("FB");
elif num%fizz_mod == 0:
out.append("F");
elif num%buzz_mod == 0:
out.append("B");
else:
out.append(str(num));
return out;
ins = [];
out = [];
if len(sys.argv) <= 1:
#print("BAD ARGS");
sys.exit();
else:
with open(sys.argv[1]) as f:
ins = [line.strip("\n").split() for line in f];
for line in ins:
#if len(line) != 3:
#print("not enough args, line =", line);
# continue;
#try:
fizz_mod = int(line[0]);
buzz_mod = int(line[1]);
count = int(line[2]);
#except ValueError:
#print("could not use line =", line);
# continue;
out.append(' '.join(fizz_buzz(fizz_mod, buzz_mod, count)));
print('\n'.join(out), end = '');
|
#!/usr/bin/env python3
# Created by: Mikayla Barthelette
# Created on: Sept 2021
# This program finds the volume of a cone
import math
def main():
# this function calculates the volume
# input
radius = int(input("Enter the radius of the cone (mm): "))
height = int(input("Enter the height of the cone (mm): "))
# process
volume = math.pi * radius ** 2 * (height / 3)
# output
print("\nThe volume of the cone is: {0} mm³.".format(volume))
print("\nDone.")
if __name__ == "__main__":
main()
|
# Uses python3
import sys
def gcd_naive(a, b):
# gcd of a,b is gcd of b%a and a ; Euclid's algorithm
if a==0:
return b
elif b == 0:
return a
else:
return gcd_naive(b%a,a)
if __name__ == "__main__":
input = sys.stdin.read()
a, b = map(int, input.split())
print(gcd_naive(a, b))
|
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 28 00:26:27 2016
@author: dahenriq
"""
import pandas as pd
import Demographics as dm
class MainScreen:
def __init__(self):
self.Badgeinput=1
self.Passwordinput=1
self.dfpopo = pd.read_csv("Police.csv",index_col='Badge')
def empty(df):
return df.empty
def plogin(self,Badgeinput,Passwordinput):
verified=False
verqry=self.dfpopo.index[self.dfpopo.index==(Badgeinput)]
# use the true/false array self.dfpopo.index==(Badgeinput) to
# index into the dataframe. if this is empty, the badge number
# doesn't exist
ver2qry=self.dfpopo[self.dfpopo.index==Badgeinput]['Password'].get_values()
# if verqry does exist, index into the Password column to retrieve
# the password
if (len(verqry.tolist()) == 0 | ver2qry != Passwordinput):
verified==False
print("\nPlease enter a valid Badge# and Password\n")
a.LoginMenu()
else:
print("\nVerified User...\n")
verified = True
a.getName(Badgeinput)
a.getPDdist(Badgeinput)
selection = self.Menu1()
return verified
def LoginMenu(self):
Badgeinput=int(input("Badge#:\n"))
Passwordinput=int(input("Password#:\n"))
a.plogin(Badgeinput,Passwordinput)
def listToStringWithoutBrackets(self,list1):
return str(list1).replace('[','').replace(']','')
def getName(self,Badgeinput):
Qname=self.dfpopo[self.dfpopo.index==Badgeinput]['LastName'].get_values()
LName=Qname.tolist()
fName=a.listToStringWithoutBrackets(LName)
fName=fName.replace("'","") # for cleanup. still not really sure why this is needed.....
print "\nWelcome Officer " + fName +"\n"
return fName
def getPDdist(self,Badgeinput):
QPDdist=self.dfpopo[self.dfpopo.index==Badgeinput]['PD District'].get_values()
LPDdist=QPDdist.tolist()
fPDdist=a.listToStringWithoutBrackets(LPDdist)
fPDdist=fPDdist.replace("'","")
print "District: "+fPDdist+"\n"
return fPDdist
def Menu1(self):
print "\nMenu\n******\n"
print "1. Demographics\n"
print "2. Crime Stats\n"
print "3. Crime Predictions\n"
print "4. Exit\n"
menu1input=int(input("Please enter Menu# (1,2,3,4):\n"))
if menu1input==1:
#b.Crosstab(a.Badgeinput)#UNSURE OF CALL LOGIC/SYNTAX
#b.BarChart()
#b.ByPd()#Prints object location instead of values??
b.PdDemo()
a.Menu1()
else:
exit()
# Will Need - CrimeStats Class, and a Crime Predictions class.
# based on what the user inputs, you would instantiate the given class and do stuff with it.
# Ex.
# if(menu1input == 1):
# a = Demographics()
# ((No sub menu)show summary stats for logged in officers district grouped by zip-#Crimes,Pop 2013, Pop Density, unemployment rate etc.
# Provide option to print stats to csv)
#
#elif(menu1input == 2):
# a = CrimeStats
# (Sub menu - options )
#
#elif(menu1input == 3):
# a = CrimePredictions
# (Sub menu - options)
#
# return menu1input
#
#
# Using subclasses for the submenu items ex. item 2 submenu will be
# a class that inherits from the item 2 class. This should satisy "inheritance" as per grading rubric
#
# So with this proposed structure we will have four files: one for each menu item class and then this one.
# we will have three additional import statements that might be
# import Demographcs() Danielle coded
# import CrimeStats() Siddhant??- I provided suggested menu choices please feel free to edit
# import CrimePredictions() Rushil?? -Please let me know what you would like for your menu options
#TestMain
a=MainScreen()
b=dm.Demographics()
print("San Francisco PD\nLogin\n")
a.LoginMenu()
|
""" solve sudoku puzzle"""
import itertools
import numpy as np
class sudoku_puzzle:
"""sudoku puzzle and solve method"""
def __init__(self, init_puzzle="none"):
self.olist = [0, 1, 2, 3, 4, 5, 6, 7, 8]
self.ilist = list(itertools.chain.from_iterable(itertools.repeat(x, 9) for x in self.olist))
self.jlist = self.olist[:] * 9
self.puzzle = np.empty((9, 9), dtype=object)
self.puzzle.fill([1, 2, 3, 4, 5, 6, 7, 8, 9])
if not init_puzzle == "none":
self.merge(init_puzzle.puzzle)
def __str__(self):
puzzle_str = ""
for i in range(9):
for j in range(9):
puzzle_str += str("%i" %self.puzzle[i, j])+","
puzzle_str += "\n"
puzzle_str
return puzzle_str
def merge(self, puzzle2):
"""merge two sudoku puzzle"""
for i, j in zip(self.ilist, self.jlist):
if isinstance(self.puzzle[i, j], int):
continue
else:
if isinstance(puzzle2[i, j], int):
self.puzzle[i, j] = puzzle2[i, j]
continue
self.puzzle[i, j] = [x for x in self.puzzle[i, j] if x in puzzle2[i, j]]
def solve_elim(self):
"""solve the puzzle by elimination"""
for i, j in zip(self.ilist, self.jlist):
if isinstance(self.puzzle[i, j], int):
continue
if isinstance(self.puzzle[i, j], list):
if len(self.puzzle[i, j]) == 1:
self.puzzle[i, j] = self.puzzle[i, j][0]
continue
if isinstance(self.puzzle[i, j], list):
i2list = [x for x in range(9)]
i2list.remove(i)
j2list = [x for x in range(9)]
j2list.remove(j)
# ----------------
for i2 in i2list:
if isinstance(self.puzzle[i2, j], int):
try:
self.puzzle[i, j].remove(self.puzzle[i2, j])
except:
pass
for j2 in j2list:
if isinstance(self.puzzle[i, j2], int):
try:
self.puzzle[i, j].remove(self.puzzle[i, j2])
except:
pass
for i3 in range(int(i/3)*3, int(i/3)*3+3):
for j3 in range(int(j/3)*3, int(j/3)*3+3):
if isinstance(self.puzzle[i3, j3], int):
try:
self.puzzle[i, j].remove(self.puzzle[i3, j3])
except:
pass
def main():
"""main precess of the solver"""
pass
if __name__=="__main__":
import sample2
init_puzzle = sample2.main()
puz = sudoku_puzzle(init_puzzle)
for i in range(100):
puz.solve_elim()
print(puz)
|
import RPi.GPIO as gpio
gpio.setmode(gpio.BOARD)
gpio.setup(7, gpio.IN)
gpio.setup(5, gpio.OUT)
while True:
input_value = gpio.input(7)
if input_value == False:
print('The button has been pressed...')
gpio.output(5,gpio.HIGH)
else
gpio.output(5,gpio.LOW)
|
print("\n----------------------------------- BFS (Breadth-First Search) ----------------------------------- ")
from collections import deque
#STATION
class Station:
# variables
def __init__(self, name):
self.name = name
self.neighbors = []
def add_connection(self, another_station):
# put another station in neighbors in self class
self.neighbors.append(another_station)
# put self in neighbors in another_station
another_station.neighbors.append(self)
# Breadth-First Search Algorithms
def bfs(start, goal):
# variables
previous = {}
queue = deque() # station list
current = None
# initial setting
previous[start] = None # key if from value station
queue.append(start)
# look if there is unseen station and doesn't find the destination yet
while len(previous) > 0 and current != goal: # done if false (continue if true)
current = queue.popleft()
for neighbor in current.neighbors:
if neighbor not in previous.keys():
queue.append(neighbor)
previous[neighbor] = current
if goal == current:
path = [goal]
start = previous[goal] # previous[current] = previous station
path.append(start)
while previous[start] != None:
path.append(previous[start])
start = previous[start]
return path
else:
return None
#READ
stations = {}
in_file = open('stations.txt')
# loop for subway line
for line in in_file:
data_w_space = line.strip().split(" - ")
previous_station = None
# loop for stations
for name in data_w_space:
station_name = name.strip()
# register key & instance into dictionary if it's not registered yet
if station_name not in stations.keys():
current_station = Station(station_name) # current_station의 이름은 station_name이다. add_connection에 쓸 수 있도록 current_station 설정
stations[station_name] = current_station # 사전 등록: stations 사전에 역 이름 (current station instance)를 등록
else:
current_station = stations[station_name] # current_station을 역 이름 (value)로 전환
# connect neighbor stations add_connection
if previous_station != None: # 첫번째 역은 연결시킬 필요가 없음
current_station.add_connection(previous_station) # 현재 역과 전 역을 neighbor로 추가
# convert current station to prev station
previous_station = current_station
in_file.close()
# TEST
start_name = input("Start:")
goal_name = input('Destination:')
start = stations[start_name]
goal = stations[goal_name]
path = bfs(start, goal)
for station in path:
print(station.name)
|
n1 = int(input("digite nota 1 "))
n2 = int(input("digite nota 2 "))
n3 = int(input("digite nota 3 "))
r= (n1+n2+n3)/3
print(r)
|
list_val = ( 'jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec')
i = raw_input("enter a value")
i = int(i)
end= i * 3
start= end - 3
print list_val[start:end]
|
n=int(input("Enter a number"))
n1,n2=0,1
count=0
if n<=0:
print("Enter a positive number")
elif n==1:
print("fibonacci sequemce upto n terms:",n)
print(n1)
else:
print("Fibonacci series")
while count<n:
print(n1)
nth=n1+n2
n1=n2
n2=nth
count=count+1
|
my_set = {1,2,3}
print (my_set)
#set dengan dengan fungsi set
my_set = set([1,2,3])
print (my_set)
#set dengan data campuran
my_set = {1,2,3, "python" ,(3,4,5)}
print (my_set)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Implémentation d'un graphe non orienté à l'aide d'un dictionnaire: les clés
sont les sommets, et les valeurs sont les sommets adjacents à un sommet donné.
Les boucles sont autorisées. Les poids ne sont pas autorisés.
On utilise la représentation la plus simple: une arête {u, v} sera présente
deux fois dans le dictionnaire: v est dans l'ensemble des voisins de u, et u
est dans l'ensemble des voisins de v.
"""
class GrapheOriente(object):
def __init__(self):
"""Initialise un graphe sans arêtes"""
self.dictionnaire = dict()
def ajouter_arc(self, u, v):
"""Ajoute une arête entre les sommmets u et v, en créant les sommets
manquants le cas échéant."""
# vérification de l'existence de u et v, et création(s) sinon
if u not in self.dictionnaire:
self.dictionnaire[u] = set()
if v not in self.dictionnaire:
self.dictionnaire[v] = set()
# ajout de u (resp. v) parmi les voisins de v (resp. u)
self.dictionnaire[u].add(v)
def ajouter_arcs(self, iterable):
"""Ajoute toutes les arêtes de l'itérable donné au graphe. N'importe
quel type d'itérable est acceptable, mais il faut qu'il ne contienne
que des couples d'éléments (quel que soit le type du couple)."""
for u, v in iterable:
self.ajouter_arc(u, v)
def ajouter_sommet(self, sommet):
"""Ajoute un sommet (de n'importe quel type hashable) au graphe."""
self.dictionnaire[sommet] = set()
def ajouter_sommets(self, iterable):
"""Ajoute tous les sommets de l'itérable donné au graphe. N'importe
quel type d'itérable est acceptable, mais il faut qu'il ne contienne
que des éléments hashables."""
for sommet in iterable:
self.ajouter_sommet(sommet)
def arcs(self):
"""Renvoie l'ensemble des arêtes du graphe. Une arête est représentée
par un tuple (a, b) avec a <= b afin de permettre le renvoi de boucles.
"""
return {
tuple((u, v)) for u in self.dictionnaire
for v in self.dictionnaire[u]
}
def boucles(self):
"""Renvoie les boucles du graphe, c'est-à-dire les arêtes reliant un
sommet à lui-même."""
return {(u, u) for u in self.dictionnaire if u in self.dictionnaire[u]}
def contient_arc(self, u, v):
"""Renvoie True si l'arête {u, v} existe, False sinon."""
if self.contient_sommet(u) and self.contient_sommet(v):
return u in self.dictionnaire[v] # ou v in self.dictionnaire[u]
return False
def contient_sommet(self, u):
"""Renvoie True si le sommet u existe, False sinon."""
return u in self.dictionnaire
def degre(self, sommet):
"""Renvoie le nombre de voisins du sommet; s'il n'existe pas, provoque
une erreur."""
return len(self.dictionnaire[sommet])
def nombre_arcs(self):
"""Renvoie le nombre d'arêtes du graphe."""
return len(self.arcs())
def nombre_boucles(self):
"""Renvoie le nombre d'arêtes de la forme {u, u}."""
return len(self.boucles())
def nombre_sommets(self):
"""Renvoie le nombre de sommets du graphe."""
return len(self.dictionnaire)
def retirer_arc(self, u, v):
"""Retire l'arête {u, v} si elle existe; provoque une erreur sinon."""
self.dictionnaire[u].remove(v) # plante si u ou v n'existe pas
# plante si u ou v n'existe pas
def retirer_arcs(self, iterable):
"""Retire toutes les arêtes de l'itérable donné du graphe. N'importe
quel type d'itérable est acceptable, mais il faut qu'il ne contienne
que des couples d'éléments (quel que soit le type du couple)."""
for u, v in iterable:
self.retirer_arc(u, v)
def retirer_sommet(self, sommet):
"""Efface le sommet du graphe, et retire toutes les arêtes qui lui
sont incidentes."""
del self.dictionnaire[sommet]
# retirer le sommet des ensembles de voisins
for u in self.dictionnaire:
self.dictionnaire[u].discard(sommet)
def retirer_sommets(self, iterable):
"""Efface les sommets de l'itérable donné du graphe, et retire toutes
les arêtes incidentes à ces sommets."""
for sommet in iterable:
self.retirer_sommet(sommet)
def successeurs(self, sommet):
return sorted( [i for i in self.dictionnaire[sommet]])
def predecesseurs(self, sommet):
res = []
for v in self.dictionnaire:
if sommet in self.dictionnaire[v]:
res.append(v)
return res
def degre_entrant(self, sommet):
return len(self.predecesseurs(sommet))
def degre_sortant(self, sommet):
return len(self.successeurs(sommet))
def sommets(self):
"""Renvoie l'ensemble des sommets du graphe."""
return set(self.dictionnaire.keys())
def sous_graphe_induit(self, iterable):
"""Renvoie le sous-graphe induit par l'itérable de sommets donné."""
G = GrapheOriente()
G.ajouter_sommets(iterable)
for u, v in self.arcs():
if G.contient_sommet(u) and G.contient_sommet(v):
G.ajouter_arc(u, v)
return G
def voisins(self, sommet):
"""Renvoie l'ensemble des voisins du sommet donné."""
return self.dictionnaire[sommet]
def aux1(graphe, depart, d_v, parents):
resultat = list()
d_v[depart]=1
for v in graphe.successeurs(depart):
if d_v[v]!=1:
resultat+=aux1(graphe,v,d_v,parents)
parents[v]=depart
resultat.append(depart)
return resultat
def parcours_profondeur_oriente(graphe):
d_v={u:0 for u in graphe.sommets()}
parents=dict()
depart=list(graphe.sommets())[0]
sommets = aux1(graphe, depart, d_v, parents)
for v in graphe.sommets():
if d_v[v]!=1:
sommets += aux1(graphe, v, d_v, parents)
return (sommets, parents)
def test_suite(graphe, u):
for i, j in graphe.arcs():
if u == j:
return True
return False
def nettoyer_cycle(graphe):
for u,v in graphe.arcs():
if not test_suite(graphe, u):
graphe.retirer_arc(u, v)
def aux2(graphe, sommet, status, cycle):
if status[sommet]==1:
return True
if status[sommet]==0:
return False
status[sommet]=1
for v in graphe.successeurs(sommet):
if aux2(graphe, v, status, cycle):
cycle.ajouter_arc(sommet,v)
return True
status[sommet]=0
return False
def detection_cycle(graphe):
status={u:-1 for u in graphe.sommets()}
cycle=type(graphe)()
for u in graphe.sommets():
if aux2(graphe, u, status, cycle) == True :
nettoyer_cycle(cycle)
return cycle
def parcours_profondeur_oriente_date(graphe,depart,dates,instant):
dates[depart] = 0
for v in graphe.successeurs(depart):
if(dates[v] == -1):
parcours_profondeur_oriente_date(graphe ,v, dates,instant)
dates[depart] =instant[0]
instant[0] += 1
def profondeur_dates(graphe):
dates = dict()
instant = dict()
instant[0] = 1
for sommet in graphe.sommets():
dates[sommet] = -1
for v in graphe.sommets():
if(dates[v] == -1):
parcours_profondeur_oriente_date(graphe,v,dates,instant)
return dates
def renversement(graphe):
graphe_bis = GrapheOriente()
ensemble = graphe.arcs()
for v in ensemble:
graphe_bis.ajouter_arc(v[1] , v[0])
return graphe_bis
def parcours_profondeur_oriente_rec(graphe,depart,deja_visites):
sommets = list()
deja_visites[depart] = True
for v in graphe.successeurs(depart):
if(not deja_visites[v]):
sommets += (parcours_profondeur_oriente_rec(graphe ,v, deja_visites))
sommets.append(depart)
return sommets
def composantes_fortement_connexes(graphe):
CFC = list()
deja_visites = dict()
dates = dict()
dates = profondeur_dates(graphe)
graphe_bis = renversement(graphe)
for sommet in graphe.sommets():
deja_visites[sommet] = False
sommets = sorted(dates.items(), key=lambda colonne: colonne[1] , reverse = True)
for v in sommets:
if(not deja_visites[v[0]]):
deja_visites[v[0]] = True
CFC.append(parcours_profondeur_oriente_rec(graphe_bis,v[0],deja_visites))
return CFC
|
from abc import ABC, abstractmethod
class MenuComponent(ABC):
'''Item do cardápio, com sub-itens'''
def append(self, item):
'''incluir sub-item'''
raise NotImplementedError()
def remove(self, item):
'''remover sub-item'''
raise NotImplementedError()
def __getitem__(self, i):
'''obter sub-item pelo índice'''
raise NotImplementedError()
@property
@abstractmethod
def name(self):
'''obter nome do item'''
@property
@abstractmethod
def description(self):
'''obter descrição do item'''
@property
def price(self):
'''obter preço do item'''
raise NotImplementedError()
@property
@abstractmethod
def is_vegetarian(self):
'''obter booleano indicador de item vegetariano'''
@abstractmethod
def display(self):
'''exibir item e sub-itens'''
|
"""
Um trem é um iterável com vagões.
O construtor pede o número de vagões::
>>> t = Trem(3)
O trem é um iterável::
>>> it = iter(t)
E o iterador obtido devolve vagões::
>>> next(it)
'vagão #1'
>>> next(it)
'vagão #2'
>>> next(it)
'vagão #3'
Somente a quantidade correta de vagões é devolvida::
>>> next(it)
Traceback (most recent call last):
...
StopIteration
Finalmente, podemos percorrer um trem num laço ``for``::
>>> for vagao in Trem(3):
... print(vagao)
...
vagão #1
vagão #2
vagão #3
"""
class Trem:
def __init__(self, qt_vagoes):
self.qt_vagoes = qt_vagoes
def __iter__(self):
for i in range(self.qt_vagoes):
yield 'vagão #{}'.format(i + 1)
|
#!/usr/bin/env python3.6
""" Primero preparamos el entorno, realizamos los siguientes pasos :
1 Creamos un servidor usando librería standar de PYTHON :
python -m SimpleHTTPServer 5500
2 Instalamos lsof para ver todos los procesos que están abiertos
Ejemplos LSOF (https://www.howtoforge.com/linux-lsof-command/) """
import subprocess
import os
from argparse import ArgumentParser
parser = ArgumentParser(description='kill the running process listening on a given port')
parser.add_argument('port', type=int, help='the port number to search for')
port = parser.parse_args().port
try:
result = subprocess.run(
['lsof', '-n', "-i4TCP:%s" % port],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
except subprocess.CalledProcessError:
print(f"No process listening on port {port}")
else:
listening = None
for line in result.stdout.splitlines():
if "LISTEN" in str(line):
listening = line
break
if listening:
# PID is the second column in the output
pid = int(listening.split()[1])
os.kill(pid, 9)
print(f"Killed process {pid}")
else:
print(f"No process listening on port {port}")
|
class Student:
def __init__(self, id, grades):
self.__id = id
self.__grades = grades
def __lt__(self, obj):
grade1 = 0
grade2 = 0
for grade in self.__grades:
grade1 += grade
grade1 /= len(self.__grades)
for grade in obj.__grades:
grade2 += grade
grade2 /= len(obj.__grades)
return grade1 < grade2
def __str__(self):
return "Student ID: {}\nGrades: {}".format(self.__id, self.__grades)
a = Student(1, [3.0, 4.6, 3.4, 5.4])
b = Student(2, [9.5, 9.0, 8.9, 9.8])
print(a < b)
|
d = int(input("Type in the exercise you want to run: "))
if(d == 1):
# find_min function definition goes here
def find_min(num1, num2):
if(num1 > num2):
return num2
else:
return num1
first = int(input("Enter first number: "))
second = int(input("Enter second number: "))
# Call the function here
minimum = find_min(first, second)
print("Minimum: ", minimum)
elif(d == 2):
# Your function definition goes here
def upper_fun(user_input):
upper_count = 0
for i in user_input:
if i.isupper():
upper_count += 1
return upper_count
def lower_fun(user_input):
lower_count = 0
for i in user_input:
if i.islower():
lower_count += 1
return lower_count
user_input = input("Enter a string: ")
# Call the function here
upper = upper_fun(user_input)
lower = lower_fun(user_input)
print("Upper case count: ", upper)
print("Lower case count: ", lower)
elif(d == 3):
e = 2
elif(d == 4):
e = 2
elif(d == 5):
e = 2
elif(d == 6):
e = 2
|
def count_eights(num_list):
return num_list.count(8)
def adj(num_list):
for i, num in enumerate(num_list):
if(num == 8 and i != len(num_list)-1):
if(num_list[i+1] == 8):
return True
return False
def list_num(list_str):
num_list = []
try:
for element in list_str:
num_list.append(int(element))
return num_list
except:
print("Error - please enter only integers.")
return []
def main():
list_str = input("Enter elements of list separated by commas: ").split(",")
num_list = list_num(list_str)
if(num_list != []):
if(count_eights(num_list) > 1):
if(adj(num_list)):
print("True")
else:
print("False")
else:
print("False")
main()
|
def to_int(a_list):
int_list = []
for i in a_list:
int_list.append(int(i))
return int_list
def even_list(a_list):
return [i for i in a_list if not i%2]
def even_sum(a_list):
a_list = to_int(a_list)
a_list_even = even_list(a_list)
return sum(a_list_even)
def get_list():
a_list = input("Enter elements of list separated by commas: ").strip().split(',')
return a_list
# Main program starts here - DO NOT change it
a_list = get_list()
print(even_sum(a_list))
|
# Constants
DIM = 4 # dimension of the board DIMxDIM
EMPTYSLOT = 0
QUIT = 0
def initialize_board():
''' Creates the initial board according to the user input.
The board is a list of lists.
The list contains DIM elements (rows), each of which contains DIM elements (columns)'''
numbers = input().split()
numbers = [int(number) for number in numbers]
puzzle_board = []
index = 0
for _ in range(DIM):
row = numbers[index:index + DIM]
index += DIM
puzzle_board.append(row)
return puzzle_board
def display(puzzle_board):
''' Display the board, printing it one row in each line '''
print()
for i in range(DIM):
for j in range(DIM):
if puzzle_board[i][j] == EMPTYSLOT:
print("\t", end="")
else:
print(str(puzzle_board[i][j]) + "\t", end="")
print()
print()
def get_current_pos(puzzle_board, num):
for i in range(DIM):
for j in range(DIM):
if(puzzle_board[i][j] == num):
return (i, j)
def get_new_pos(puzzle_board, num, current_pos):
i, j = current_pos
if(j < DIM - 1 and puzzle_board[i][j+1] == EMPTYSLOT): #right
return (i, j+1)
if(j > 0 and puzzle_board[i][j-1] == EMPTYSLOT): #left
return (i, j-1)
if(i < DIM - 1 and puzzle_board[i+1][j] == EMPTYSLOT): #down
return (i+1, j)
if(i > 0 and puzzle_board[i-1][j] == EMPTYSLOT): #up
return (i-1, j)
return None
def move(puzzle_board, current_pos, new_pos, num):
c_i, c_j = current_pos
n_i, n_j = new_pos
puzzle_board[c_i][c_j] = EMPTYSLOT
puzzle_board[n_i][n_j] = num
def update_board(num, puzzle_board):
current_pos = get_current_pos(puzzle_board, num)
new_pos = get_new_pos(puzzle_board, num, current_pos)
if new_pos != None:
move(puzzle_board, current_pos, new_pos, num)
def main():
puzzle_board = initialize_board()
num = -1
while num != QUIT:
display(puzzle_board)
num = int(input())
update_board(num, puzzle_board)
main()
|
"""
PW3
name: 3.student.mark.oop.math.py
Use math module
Use numpy
Calculate GPA for given student
Sort student list by GPA descending
Decorate UI
"""
# ! usr/bin/python3
import math
import numpy as np
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Classes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Student class - Parent class
class Student:
# Contructor
def __init__(self, sid, sname, sdob, gpa=0):
self.sid = sid
self.sname = sname
self.sdob = sdob
self.gpa = gpa
# Get methods
def get_sid(self):
return self.sid
def get_sname(self):
return self.sname
def get_sdob(self):
return self.sdob
def get_gpa(self):
return self.gpa
# Set methods
def set_gpa(self, gpa):
self.gpa = gpa
# Course class - Parent class
class Course:
# Contructor
def __init__(self, cid, cname, credit):
self.cid = cid
self.cname = cname
self.credit = credit
# Get methods
def get_cid(self):
return self.cid
def get_cname(self):
return self.cname
def get_credit(self):
return self.credit
# Mark class - Child class
class Mark():
# Contructor
def __init__(self, student, course, value):
self.student = student
self.course = course
self.value = value
# Get methods
def get_value(self):
return self.value
def get_student(self):
return self.student
def get_course(self):
return self.course
# Driver class
class Driver():
# Class variable
# List to store information of students
students = []
# List to store information of courses
courses = []
# List to store information of marks
marks = []
# Class variable
nofstudents = None
nofcourses = None
##### Input functions (5)
# Function to input number of students
def input_number_students(self):
while True:
try:
self.nofstudents = int(input("Enter number of students: "))
while self.nofstudents <= 0:
print("Number of students has to be positive integer!!!\n")
self.nofstudents = int(input("Enter again number of students: "))
except:
print("Number of students has to be positive integer!!!\n")
else:
break
# Function to input number of courses
def input_number_courses(self):
while True:
try:
self.nofcourses = int(input("Enter number of courses: "))
while self.nofcourses <= 0:
print("Number of couses has to be positive integer!!!\n")
self.nofcourses = int(input("Enter again number of courses: "))
except:
print("Number of courses has to be positive integer!!!\n")
else:
break
# Function to input information of students
def input_students_infor(self):
if self.nofstudents <= 0:
print("Student list is empty. Please enter number of students!!!")
elif self.nofstudents > len(self.students):
for i in range(0, self.nofstudents):
print(f"Enter information of student #{i + 1}")
while True:
try:
sid = int(input(f"Enter student id: "))
while sid <= 0:
sid = int(input(f"ID must be positive. Enter again student id: "))
except:
print("ID has to be positive integer!!!")
else:
break
while True:
try:
sname = input(f"Enter name of student #{sid}: ")
while len(sname) == 0:
sname = input(f"Student name can't be empty.Enter agian name of student #{sid}: ")
except:
print(f"Student name can't be empty.Enter agian name of student #{sid}: ")
else:
break #Still not good!!!Name is still entered by numbers
while True:
try:
sdob = input(f"Enter date of birth of student #{sid}: ")
while len(sdob) == 0:
sdob = input(f"Student name can't be empty.Enter agian name of student #{sid}: ")
except:
print("Student name can't be empty.Enter again name of student!!!")
else:
break #Still not good!!!Dob is still entered by letters
self.students.append(Student(sid, sname, sdob))
else:
print(f"The student list is full({len(self.students)} students).Please use function 1 to extra student list")
# Function to input information of courses
def input_courses_infor(self):
if self.nofcourses <= 0:
print("Course list is empty. Please enter number of courses!!!")
elif self.nofcourses > len(self.courses):
for i in range(0, self.nofcourses):
print(f"Enter information of course #{i + 1}")
while True:
try:
cid = int(input(f"Enter course id: "))
while cid <= 0:
cid = int(input(f"Enter again course id: "))
except:
print("Course id must be positive integer!!!")
else:
break
while True:
try:
cname = input(f"Enter name of course #{cid}: ")
while len(cname) == 0:
cname = input(f"Name of course can't be empty.Enter name of course #{cid}: ")
except:
print(f"Name of course can't be empty.Please enter name of course #{cid}!!! ")
else:
break
while True:
try:
credit = int(input(f"Enter credit of course #{cid}: "))
while credit <= 0:
credit = int(input(f"Credit of Course is positive.Enter again credit of course: "))
except:
print(f"Credit of Course is positive.Please enter again credit of course #{cid}!!!")
else:
break
self.courses.append(Course(cid, cname, credit))
else:
print(f"The list of courses is full({len(self.courses)} courses).Please use function 2 to extra student list")
# Function to input mark of exactly courses for students
def input_mark(self):
while True:
try:
cid = int(input("Enter id of course you want to input mark: "))
while cid <= 0:
cid = int(input("Course id must be positive.Enter again course id you want to input mark: "))
except:
print("Course id must be positive.Please enter again course id you want to input mark!!!")
else:
break
for course in self.courses:
if course.get_cid() == cid:
for student in self.students:
while True:
try:
value = float(input(f"Enter mark of course {cid} for student {student.get_sname()}: "))
while value < 0:
value = float(input("Mark must not be negative\n " \
f"Enter again mark of course {cid} for student {student.get_sname()}: "))
except:
print("Mark must not be negative\n " \
f"Enter again mark of course {cid} for student {student.get_sname()}!!!")
else:
break
#Round-down student scores to 1-digit decimal
value = math.floor(value * 10)/10.0
self.marks.append(Mark(student, course, value))
else:
print("Course id is not existed!!!")
# Function to calculate GPA for given student
def calculate_GPA(self):
while True:
try:
sid = int(input(f"Enter student id you want to calculate GPA: "))
while sid <= 0:
sid = int(input(f"ID must be positive. Enter again student id: "))
check = 0
for mark in self.marks:
if check == (len(self.marks) - 1):
print(f"Error. Student id {sid} not existed!!!")
break
elif sid != mark.get_student().get_sid():
check = check + 1
else:
print("Student id is existed!!!")
except:
print("ID must be positive. Enter again student id!!!")
else:
break
list_score = np.array([])
list_credit = np.array([])
check = 0
for mark in self.marks:
if sid == mark.get_student().get_sid():
list_score = np.append(list_score, mark.get_value())
list_credit = np.append(list_credit, mark.get_course().get_credit())
gpa = np.dot(list_score, list_credit) / np.sum(list_credit)
for student in self.students:
if sid == student.get_sid():
student.set_gpa(gpa)
# Function to sort student list by GPA decrending
def sort_student_list(self):
if len(self.students) == 0:
print("List of student information is empty!!!")
else:
data_type = [('sid', 'S30'), ('sname', 'S30'), ('gpa', float)]
new_students = []
for student in self.students:
new_student_infor = (student.get_sid(), student.get_sname(), student.get_gpa())
new_students.append(new_student_infor)
sorting_new_students = np.array(new_students, dtype=data_type)
sorted_list = np.sort(sorting_new_students, order = 'gpa')
print(sorted_list)
#### Display functions (3)
# Function to list all student's informations
def list_students(self):
if len(self.students) == 0:
print("The student list is empty!!!")
else:
print("Student id", "Student name", "Student dob", sep=" ")
for student in self.students:
print(f"{student.get_sid()}" ,
f"{student.get_sname()}" ,
f"{student.get_sdob()}", sep=" ")
# Function to list all course's informations
def list_courses(self):
if len(self.courses) == 0:
print("The course list is empty!!!")
else:
for course in self.courses:
print(f"Course id: {course.get_cid()}" \
f"Course name: {course.get_cname()}", sep=" - ")
# Function to list student marks for a given course
def list_mark(self):
if len(self.marks) == 0:
print("The mark list is empty!!!")
else:
while True:
try:
cid = int(input("Enter id of course you want to list marks: "))
while cid <= 0:
cid = int(input("Course id must be positive.Enter again course id you want to list marks: "))
check = 0
for mark in self.marks:
if check == (len(self.marks) - 1):
print("Error")
break
elif cid != mark.get_course().get_cid():
check = check + 1
else:
print("Course id is existed!!!")
except:
print("Course id must be positive.Enter again course id you want to list marks!!!")
else:
break
for mark in self.marks:
if cid == mark.get_course().get_cid():
print(mark.get_student().get_sname(), mark.get_course().get_cname(), mark.get_value(), sep="-")
# Function to run the program
def run_Driver(self):
print("Please select operation: \n" \
"1.Input number of students \n" \
"2.Input number of courses \n" \
"3.Input information for students \n" \
"4.Input information for courses \n" \
"5.Input mark for given courses \n" \
"6.Calculate GPA for given student\n" \
"7.Sort student by gpa\n" \
"8.List students \n" \
"9.List courses \n" \
"10.List marks \n" \
"11.Exist!!!" , )
while True:
select = int(input("Select operations form 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11:"))
if select == 1:
self.input_number_students()
elif select == 2:
self.input_number_courses()
elif select == 3:
self.input_students_infor()
elif select == 4:
self.input_courses_infor()
elif select == 5:
self.input_mark()
elif select == 6:
self.calculate_GPA()
elif select == 7:
self.sort_student_list()
elif select == 8:
self.list_students()
elif select == 9:
self.list_courses()
elif select == 10:
self.list_mark()
elif select == 11:
print("Existed!!!")
break
else:
print("Invalid value")
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Main ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if __name__ == "__main__":
# Create object driver
d = Driver()
d.run_Driver()
|
#! usr/bin/python3
students = []
students_name = []
courses = []
courses_id = []
marks = []
def input_number_student():
nofstudent = int(input("Enter number of students: "))
return nofstudent
def input_number_course():
nofcourse = int(input("Enter number of courses: "))
return nofcourse
number_of_student = input_number_student()
number_of_course = input_number_course()
def input_student_infor():
for i in range(1, number_of_student+1):
sid = input(f"Enter student #{i} id: ")
sname = input(f"Enter student #{i} name: ")
sdob = input(f"Enter student #{i} date of birth: ")
student = [sid, sname, sdob]
students.append(student)
students_name.append(sname)
def input_course_infor():
for i in range(1, number_of_course+1):
print(f"Enter information of course #{i}:")
cid = int(input("Enter course id: "))
cname = input("Enter course name: ")
course = [cid, cname]
courses.append(course)
courses_id.append(cid)
def input_mark():
cid = int(input("Enter course id you want to input mark: "))
if cid in courses_id:
for i in range(0, number_of_student):
input_mark = input(f"Enter mark of course {cid} for student {students_name[i]} :")
mark_input = [cid, students_name[i], input_mark]
marks.append(mark_input)
def list_coures():
for i in range(courses):
print(f"Course information {i}: ")
print(courses[i])
def list_students():
for i in range(students):
print(f"Student information {i}: ")
print(students[i])
def output_mark():
kk = int(input("Enter course id you want to display: "))
if kk in courses_id:
for each_item in marks:
for nested_item in each_item:
if nested_item == kk:
print(each_item)
input_student_infor()
input_course_infor()
input_mark()
output_mark()
|
'''enumerate_and_zip.py -- explainer for enumerate and zip functions
Ben Rose
2017-06-08
Python3.6
'''
#set up lists
a = [4, 5, 6, 7 , 8]
name = ['Isabel', 'Liam', 'Jade', 'Mia', 'Ethan']
#show how `enumerate` works
print('Example of enumerate()')
for i, num in enumerate(a):
print(i, num)
#Loop through two lists together with `enumerate`
print('\nLooping through two lists') #Adds a blank line for a clean output
for i, age in enumerate(a):
print(f'{name[i]} is {age} years old.')
#Loop through two lists with zip
print('\nLooping through two lists is better with zip')
for b in zip(name, a):
print(f'{b[0]} is {b[1]} years old.')
|
#! python3
# mapIt.py - Launches a map in the browser using an address from the
# command line or clipboard
import webbrowser, sys, pyperclip
if len(sys.argv) > 1:
# get address from the command line.
address = ' '.join(sys.argv[1:])
else:
#get address from the clipboard
address = pyperclip.paste()
webbrowser.open('http://www.google.com/map/place/' + address)
webbrowser.open('http://wwww.learnenough.com/command-line-tutorial/basics' + address)
webbrowser.open('https://medium.com/@thedancercodes/our-watch-has-ended-the-converge-journey-750e980b4db0' + address)
|
#program that counts the number of characters in a message
import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0) #sets the default value as 0
count[character] = count[character] + 1 #updating
pprint.pformat(count)
#PRETTY PRINT
# 1. import the pprint module
# 2. Substitute the print() function with pprint() function
# 3. Kind of like sorting, use the pformat() function for order
|
#the isX string methods
while True:
print('Enter your age: ')
age = input()
if age.isdecimal():
break
print('Please enter a number for your age.')
while True:
print('Select a new password (letters and numbers only): ')
password = input()
if password.isalnum():
break
print('Passwords can only have letters and numbers')
'''
isalpha() - returns TRUE only letters and it is not blank
isalnum() - returns TRUE only letters and numbers and is not blank
isdecimal() - returns TRUE consists of numeric characters and is not empty
isspace() - returns TRUE if string consists of only spaces, tabs, new-lines and is not blank
istitle() - returns TRUE if the string consists of words that begin with uppercase letters followed by lowercase letters
'''
|
from passlib.hash import pbkdf2_sha256
def create(conn, email, username, password_hash, date):
cursor = conn.cursor()
cursor.execute("""SELECT username FROM user WHERE username = ?""", [username])
result = cursor.fetchone()
if result is not None and result['username'] == username:
return False
cursor.execute("""INSERT INTO user VALUES (?, ?, ?, ?, ?)""",
[None, email, username, password_hash, date])
conn.commit()
return True
def login(conn, username, password):
cursor = conn.cursor()
cursor.execute("""SELECT * FROM user WHERE username = ?""",[username])
result = cursor.fetchone()
# Username did not match with anything in the database.
if not result:
return False
# Password did not match with the password hash in the database.
if not pbkdf2_sha256.verify(password, result['password_hash']):
return False
# Success, return the user's ID.
return result['id']
|
# extract and count paragraph <p> tags and display the count of the paragraphs as output of your program.
# test on multiple sites
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
# create context to ignore
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
# Get Url and save it into BeautifulSoup handle
url = input('Enter Url: ')
html = urllib.request.urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')
# Retrieve all paragraphs and count them
paras = soup('p')
print(len(paras))
|
#program categorizes logs email by domain name
# and uses max loop to print sender with most emails
fname = input('Enter file name: ')
try:
fh = open(fname)
except:
print('File not found:', fname)
counts = dict()
for line in fh:
words = line.split()
# print('Debug', words)
if len(words) >= 2 and words[0] == 'From':
e_address = words[1]
sbeg = e_address.find('@')
# print('slice begins at index:', sbeg)
dname = e_address[sbeg:]
counts[dname] = counts.get(dname,0)+1
print(counts)
|
#Program reads user input
#Once done is entered print out the total, count and average of the numbers inputed
#Use try and except if the user enters anything other than a number or done
#i = 0
largest = None
smallest = None
while True:
value = input('Enter a number: ')
if value == 'done':
break
try:
ivalue = int(value)
except:
print('Invalid input')
continue
#i = i + 1
if largest == None:
largest = ivalue
if smallest == None:
smallest = ivalue
if ivalue > largest:
largest = ivalue
if ivalue < smallest:
smallest = ivalue
print('Maximum is', largest)
print('Minimum is', smallest)
|
def computegrade(score):
error_msg = 'Bad score'
try:
score = float(score)
except:
return print(error_msg)
quit()
if score >= 0.0 and score <= 1.0:
if score >= 0.9:
return print('A')
elif score >= 0.8:
return print('B')
elif score >= 0.7:
return print('C')
elif score >= 0.6:
return print('D')
elif score < 0.6 and score >= 0.0:
return print('F')
else:
return print(error_msg)
score_input = input("Enter Score between 0.0 and 1.0: ")
computegrade(score_input)
|
class BankAccount:
def __init__(self, int_rate, balance):
self.int_rate = int_rate
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
else:
self.balance -= 5
print("Insufficient funds: Charging a $5 fee")
return self
def display_account_info(self):
print(f"Balance: ${self.balance}")
return self
def yield_interest(self):
if self.balance > 0:
self.balance += self.balance * self.int_rate
return self
class User:
def __init__(self, username, email_address):
self.name = username
self.email = email_address
self.account = BankAccount(int_rate=.02, balance=0)
def make_deposit(self, amount):
self.account.deposit(amount)
def make_withdrawal(self, amount):
self.account.withdraw(amount)
def display_user_balance(self):
self.account.display_account_info()
def transfer_money(self,other_user,amount):
self.account_balance -= amount
other_user.account_balance += amount
u1 = User("Alex", "[email protected]")
u1.make_deposit(100)
u1.display_user_balance()
|
#globale Variable anlegen
fehlstand = 0
"""
Sortiert ein Array mit ganzen Zahlen mittels Insertion-Sort in O(n^2)
"""
def insertionSort(list):
#global setzen
global fehlstand
for i in range(0, len(list)):
wert = list[i]
j = i
while (j > 0) and (array[j-1] > wert):
array[j] = array[j-1]
fehlstand = fehlstand + 1
j-=1
array[j] = wert
print("{}{}".format("Fehlstände: ",fehlstand) )
return array
if __name__ == "__main__":
array = list()
print("Array mit ganzen Zahlen füllen. Leere Eingabe zum Beenden.")
empty = False
#Überprüft Inputs des Benutzers bis eine leere Eingabe kommt.
while empty != True:
i = input()
if not i.strip():
empty = True
break
array.append(i)
#Caste Liste mit Strings in Int um
array = list(map(int, array))
insertionSort(array)
print(array)
|
#!/usr/bin/env python
#encoding:utf-8
__author__ = 'Samren'
"""
二分查找算法实现:对已排序的list进行二分查找
binary_search(lst, n): 查找成功,返回位置,失败,返回-1
input:
lst 要查找的list
n 要查找的数
"""
def binary_search(lst, n):
if len(lst) == 0:
return -1
low, high = 0, len(lst) - 1
while low <= high:
mid = (low + high) / 2
if lst[mid] > n:
high = mid - 1
elif lst[mid] < n:
low = mid + 1
else:
return mid
return -1
if __name__ == '__main__':
a = [1, 3, 5, 7, 9, 11]
assert(binary_search(a, 3) == 1)
assert(binary_search(a, 7) == 3)
assert(binary_search(a, 4) == -1)
|
numbers = [5,2,5,2,2]
for item in numbers:
#for item2 in range(item):
print('X'*item)
numbers = [2,2,2,8]
for item in numbers:
output = ''
for item2 in range(item):
output += 'X'
print(output)
|
weight= input('enter your weight: ')
unit= input('weight in (L)bs or (K)g: ')
if unit is 'L' or unit is 'l':
print(f"your weight is {int(weight)*0.45} kg")
elif unit is 'K' or unit is 'k':
print(f"your weight is {int(weight)/0.45} lbs")
|
# See NestedLists.png for problem definition
n = int(raw_input())
nested_list = [[raw_input(), float(raw_input())] for _ in range(n)]
scores = sorted({x[1] for x in nested_list})
second_lowest = sorted(x[0] for x in nested_list if x[1] == scores[1])
print('\n'.join(second_lowest))
|
import re
import string
def is_pangram(sentence):
if not sentence:
return False
else:
alphabet = tuple(string.ascii_lowercase)
return False not in [letter in sentence.lower() for letter in alphabet]
return True
|
family_ages = {
'Nancy' : 50,
'Alan' : 49,
'Lily' : 19,
'Allison' : 23
}
print(family_ages)
#age = family_ages['Alan'] will print the age of Alan
#print(age)
|
# Write a small script that :
# Asks the user for its name
# Asks the user for its age
# Calculates the age corresponding to the next tenth
# Tells the user, using his name, how many years remain before the next decade… (ex: “Luc, in 4 years you’ll be 50.”)
# asks the user for its gender
# if the user is a female aged more than 18, add a “Mrs.” before her name.
# if the user is a male aged more than 18, add a “Mr.” before his name.
name = input("What is your name?")
print("Hi, {}. Nice to meet you! :D".format(name))
age = int(input('How old are you?'))
next_tenth = ((age + 10) // 10 * 10)
age_dif = next_tenth - age
print("Wow! {}, in {} year(s) you'll be {}!".format(name,age_dif,next_tenth))
gender = input("Are you male of female?")
if gender in ["male", "Male"] and (age > 18):
print("Mr. {}".format(name))
elif gender in ["female", "Female"] and (age > 18):
print("Mrs. {}".format(name))
else:
print(name)
|
y=input()
x=y.lower()
if x=='a'or x=='i'or x=='o'or x=='u'or x=='e':
print("vowel")
else:
print("consonant")
|
import pygame
import math
BROWN = (130, 94, 35)
WHITE = (255, 255, 255)
class Sword(pygame.sprite.Sprite):
def __init__(self, player):
#This loads the image and converts it to a format pygame can work with easier
self.image= pygame.image.load("./items/woodensword_1.png").convert()
#Image courtesy of opengameart.com
#http://opengameart.org/content/swords-0
#Note: this image naturally points toward the direction "Left-Up,"
#This corresponds to an angle 135 degrees, or (3*pi)/4 radians, if you are so inclined
#After the 180 degree rotation coming up, the image will be at an angle of -45 degrees, or -pi/4
#A temp variable to store the individual transformations without too much loss of quality:
self.rotated_image = pygame.transform.rotate(self.image, 180)
self.image.set_colorkey(WHITE)
#Since we're rotating from the corner, the image's x and y coordinate will need to be corrected
#Rotate about the center of the player image
self.x_offset = player.rect.x / 2
self.y_offset = player.rect.y / 2
self.rect = self.image.get_rect()
#Each type is represented by a number
#1 represents main hand
#2 represents off hand
#3 represents consumable
#4 represents key item, or other
self.item_type = 1
#Base the initial positions on the player's positions
self.hilt_posx = player.rect.x
self.hilt_posy = player.rect.y
self.direction = player.direction
#Used to determine attack cooldown
#Higher = faster
#Similar to the dimensions, at some point, the "10" will be replaced with something like "sword_type.swing_speed"
self.swing_speed = 10
self.attacking = False
#An independent frame counter, though we could probably use the player's frame counter, because there will only be one sword at a time
self.frame = 0
self.frame_temp = 0
#Lastly, the number of frames it takes to swing the sword
self.expiration_frame = round(200 / self.swing_speed)
self.alive = True
def draw(self, screen, pos):
#This draw method is to be called by the inventory class,
#so as to remove the confusing between the player's attacking sword
#And the inventory's static sword
screen.blit(self.image, pos)
def attack_draw(self, screen, x_offset = 0, y_offset = 0):
#We always draw the rotated image, even if the sword isn't rotated. The update method should account for that.
if self.attacking:
screen.blit(self.rotated_image, [self.rect.x + self.x_offset + x_offset, self.rect.y + self.y_offset + y_offset])
def update(self, screen, player, frame):
"""Change the sword's position and possilby direction based on the player's positioning, as well as the sword's own frame counter"""
#We nab the info we need right away, and then have nothing to do with it after that
#Also, we check to see if we even need to update the info. After all, if we can't see the sword, there's no need to update
if self.attacking:
#First, we want to make sure that the player and the sword are on the same page in terms of direction
self.direction = player.direction
#We also need to update the position such that it always follows the player
self.rect.x = player.rect.x
self.rect.y = player.rect.y
self.x_offset = self.rect.width
self.y_offset = self.rect.height
#Then, we update our frame
if self.frame_temp != frame:
self.frame += 1
self.frame_temp = frame
if self.frame >= self.expiration_frame:
self.attacking = False
self.frame = 0
#We have to handle each direction separately
#These angles represent the rotation that has to be done at the start of the animation
#Every angle will end up being 90 degrees larger at the end of the animation
#I also decided to keep all the angles between -180 and 180 degrees, 'cuz I can
if self.direction == "L":
rotate_angle = 180 + (90 * self.frame / self.expiration_frame)
self.x_offset = -self.rect.width
self.y_offset = -self.rect.height / 4
elif self.direction == "R":
rotate_angle = 0 + (90 * self.frame / self.expiration_frame)
self.x_offset = 0
self.y_offset = 0 #self.rect.height / 4
elif self.direction == "U":
rotate_angle = 90 + (90 * self.frame / self.expiration_frame)
self.x_offset = -self.rect.width / 2
self.y_offset = -self.rect.height / 2
elif self.direction == "D":
rotate_angle = -90 + (90 * self.frame / self.expiration_frame)
self.x_offset = -self.rect.width / 2
self.y_offset = self.rect.height / 2
rotate_angle += 180
#We shouldn't need to reset the rotated image variable before this line is run
self.rotated_image = pygame.transform.rotate(self.image, rotate_angle)
#Finally, we check for expiration and reset our frame counter if we need to
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#ploting chicken location
chicken_path = 'https://assets.datacamp.com/production/repositories/2409/datasets/fa767727ef9a7b39fb9f34bee3b1bc2f02682c81/Domesticated_Hen_Permits_clean_adjusted_lat_lng.csv'
chickens = pd.read_csv(chicken_path)
# Look at the first few rows of the chickens DataFrame
print(chickens.head())
# Plot the locations of all Nashville chicken permits
plt.scatter(x = chickens.lng, y = chickens.lat)
# Show the plot
plt.show()
|
from random import randint
rand_num = randint(0,2)
print("Rock...")
print("Paper...")
print("Scissors...")
player1 = input("Player1 make your move: ")
if rand_num == 0:
computer = "rock"
elif rand_num == 1:
computer = "paper"
else:
computer = "scissors"
print(f"Computer plays {computer}")
if player1 == computer:
print("It's a tie!")
elif player1 == "rock":
if computer == "scissors":
print("Player1 wins!")
elif computer == "paper":
print("computer wins!")
elif player1 == "paper":
if computer == "rock":
print("Player1 wins!")
elif computer == "scissors":
print("computer wins!")
elif player1 == "scissors":
if computer == "paper":
print("Player1 wins!")
elif computer == "rock":
print("computer wins!")
else:
print("Something went wrong!")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import threading
import time
class ThreadA(threading.Thread):
def __init__(self, record=False, rec_time=10):
super(ThreadA, self).__init__()
self.setDaemon(True)
self.count = 0
def run(self):
while True:
self.count += 1
time.sleep(1)
print("threadA " + str(self.count))
class ThreadB(threading.Thread):
def __init__(self, record=False, rec_time=10):
super(ThreadB, self).__init__()
self.setDaemon(True)
self.count = 0
def run(self):
while True:
self.count += 1
time.sleep(2)
print("threadB " + str(self.count))
if __name__ == '__main__':
print("start events")
a = ThreadA()
a.setDaemon(True)
a.start()
b = ThreadB()
b.setDaemon(True)
b.start()
while True:
c = 1
|
# ################# NUMBER LOOP ################# #
# Write a program which repeatedly reads numbers until the user enters "done".
# Once "done" is entered, print out the total, count, and average of the numbers.
# If the user enters anything other than a number, detect their mistake using
# try and except and print an error message and skip to the next number.
# ################# NUMBER LOOP ################# #
total = 0
count = 0
while True:
given_number = input('Enter a number:\n')
if given_number.lower() == 'done':
break
try:
total += float(given_number)
count += 1
except ValueError:
print('Invalid input')
average = total/count
print('\nTotal:', total)
print('Count:', count)
print('Average:\n', average)
# ################# NUMBER LOOP - MUTATING LISTS ################# #
# Write a program which repeatedly reads numbers until the user enters "done".
# Once "done" is entered, print out the total, count, and average of the numbers.
# If the user enters anything other than a number, detect their mistake using
# try and except and print an error message and skip to the next number.
# ################# NUMBER LOOP - MUTATING LISTS ################# #
input_list = list()
while True:
input_numb = input('Enter a number: ')
if input_numb.lower() == 'done':
print('moving on...')
break
input_float = float(input_numb)
input_list.append(input_float)
average = sum(input_list) / len(input_list)
print('Average:', average)
# ################# MAX / MIN ################# #
# Write another program that prompts for a list of numbers as above and at the
# end prints out both the maximum and minimum of the numbers instead of the average.
# ################# MAX / MIN ################# #
min = None
max = None
while True:
given_number = input('\nEnter a number:\n')
if given_number.lower() == 'done':
break
try:
given_number_float = float(given_number)
if max is None or given_number_float > max:
max = given_number_float
if min is None or given_number_float < min:
min = given_number_float
except ValueError:
print('Invalid input')
print('\nMinimum:\n', min)
print('Maximum:\n', max)
|
print("Latihan 4 Bilangan acak")
from random import random
n = int(input("Masukan Nilai N: "))
for i in range(n):
while 1:
n = random()
if n < 0.5:
break
print(n)
print("Selesai")
|
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20.
def gcd(x,y): return y and gcd(y, x % y) or x
def lcm(x,y): return x * y / gcd(x,y)
n = 1
for i in range(1, 31):
n = lcm(n, i)
print(n)
|
def findMaxNum(num):
# Convert to equivalent
# binary representation
binaryNumber = bin(num)[2:]
# Stores binary representation
# of the maximized value
maxBinaryNumber = ""
# Store the count of 0's and 1's
count0, count1 = 0, 0
# Stores the total Number of Bits
N = len(binaryNumber)
for i in range(N):
# If current bit is set
if (binaryNumber[i] == '1'):
# Increment Count1
count1 += 1
else:
# Increment Count0
count0 += 1
# Shift all set bits to left
# to maximize the value
for i in range(count1):
maxBinaryNumber += '1'
# Shift all unset bits to right
# to maximize the value
for i in range(count0):
maxBinaryNumber += '0'
# Return the maximized value
return int(maxBinaryNumber, 2)
if __name__ == '__main__':
N = 11
print(findMaxNum(N))
|
#!/usr/bin/env python3
import json
import re
def input_intensity():
print("Please input scan intensity from 0 to 5 where:")
print("\t 0 - paranoid")
print("\t 1 - sneaky")
print("\t 2 - polite")
print("\t 3 - normal")
print("\t 4 - aggressive")
print("\t 5 - insane")
print("Scan intensity affects time needed to perform scan and amount of load it puts on network.")
print("While \"paranoid\" and \"sneaky\" mode may be useful for avoiding IDS alerts, they will take an extraordinarily long time to scan thousands of machines or ports.")
while True:
intensity = input("Selected scan intensity(0 - 5): ")
if int(intensity) >= 0 and int(intensity) <= 5:
return intensity
def validatePortsInput(port):
if (port.isnumeric()):
return True
else:
match = re.match(r"^[0-9]+\-[0-9]+$", port)
if (match == None):
return False
return True
def input_ports():
print("Please specify ports you want to scan.")
print("You can specify pots as range(e.g. 22-80) and specify concrete ports using comma(e.g. 22,5900). This options can be combined.")
print("\tLeave empty scan all ports (1 – 65535)")
print("\tType \"fast\" to scan 100 most common ports.")
while True:
ports = input("Input ports range: ")
ports = ''.join(ports.split())
if len(ports) == 0:
return "all"
elif ports.lower() == "fast":
return "fast"
else:
try:
for port in ports.split(','):
if not validatePortsInput(port):
raise ValueError("That is not a valid input!")
return ports
except ValueError as ve:
print(ve)
continue
def validate_ip_part(ipPart, canBeRange):
if not canBeRange and not ipPart.isnumeric():
return False
if re.match(r"^[0-9]+\-?[0-9]*$", ipPart) == None:
return False
ipParts = ipPart.split("-")
for i in ipParts:
if not i.isnumeric or int(i) < 0 or int(i) > 255:
return False
if len(ipParts) == 2 and int(ipParts[0]) >= int(ipParts[1]):
return False
return True
def validate_ip_range(ipRange):
try:
partCanBeRange = "/" not in ipRange
ipRangeParts = ipRange.split(".")
if len(ipRangeParts) != 4:
return False
if not partCanBeRange:
ipMask = int(ipRangeParts[3].split("/")[1])
if ipMask < 0 or ipMask > 32:
return False
for i in range(4):
current = ipRangeParts[i]
if i == 3 and not partCanBeRange:
current = current.split("/")[0]
if not validate_ip_part(current, partCanBeRange):
return False
return True
except Exception as ex:
print(ex)
return False
def input_ip_ranges():
print("Please specify ip ranges you want to scan.")
print("Ip ranges can be specified in multiple ways:")
print("\t* 192.168.0.0/24")
print("\t* 192.168.0.1-255")
print("\t* 192.168.0.24 (as a single address)")
ipList = set()
while True:
ip = input("Input ip range: ")
ip = ''.join(ip.split())
if len(ip) == 0 and len(ipList) != 0:
return ipList
elif len(ip) == 0 or not validate_ip_range(ip):
print("Rejected!")
continue
else:
ipList.add(ip)
def input_output_telegram_api():
return input("Please input telegram api key(empty for no output through bot): ")
def input_output_webhook_url():
return input("Please input url for output through webhook(empty for no output through webhook): ")
data = {
"scanConfig": {
"intensity": "5",
"ports": "22",
"ipList": []
},
"tgBot": {
"apiKey": ""
},
"webhook": {
"addr": ""
}
}
data["scanConfig"]["intensity"] = input_intensity()
data["scanConfig"]["ports"] = input_ports()
data["scanConfig"]["ipList"] = list(input_ip_ranges())
while True:
data["tgBot"]["apiKey"] = input_output_telegram_api()
if (data["tgBot"]["apiKey"] == ""):
print("No bot api key specified!")
continue
break
with open("config.json", "w") as write_file:
json.dump(data, write_file, indent=4)
print("Done!")
|
# -*- coding: utf-8 -*-
# takes a file and returns a string of file contents
from sys import argv
script, filename = argv
def convert(filename):
with open (filename, "r") as myfile:
data=myfile.read()
return data
|
phoneBook = dict()
n = int(input("Enter the total length of the dictionary: "))
i = 1
while (i <= n):
a = input("Contact Name: ")
b = input("Phone Number: ")
phoneBook[a] = b
i += 1
pre = '{:12} {:12}'
print(pre.format("Name", "Phone Number"))
for i in phoneBook:
print(pre.format(i, phoneBook[i]))
|
def VowCount(str): # Defines the VowCount
vow = list(str.split()) # Splits the string into list
count = 0 # Initialize count
vowel = "aeiouAEIOU" # Vowels in english alphabets
for i in vow: # For loop to check whether the elements starts with vowels or not
if i[0] in vowel:
count += 1 # Increments the count by +1
return count
print("Enter the string of line: ")
str = input()
print("Total Number of words starting with Vowels are: ", VowCount(str))
|
def cal_Mean(num):
n = len(num)
sum = 0
for i in range(0, n):
sum += int(num[i])
mean = sum/n
return mean
print("Enter the list of numbers: ")
j = input()
j = j.split()
print("The mean of the list", j, "is ", cal_Mean(j))
|
# -- DISTANCE_METRICS -- #
# -- IMPORTS -- #
import numpy as np
import math as m
# -- ARRAYS MUST BEOF SIZE (X,1) -- #
# -- DISTANCE METRICS -- #
def euclidean_distance(x,y):
"""FUNCTION::EUCLIDEAN_DISTANCE
>- Returns: The euclidean distance between the two arrays."""
return np.sqrt(np.sum(np.power(np.subtract(x,y),2),axis=-1))
def manhattan_distance(x,y):
"""FUNCTION::MANHATTAN_DISTANCE:
>- Returns: The manhattan distance (also known as L1 norm) between the two arrays."""
return np.sum(np.abs(np.subtract(x,y)),axis=-1)
def cosine_distance(x,y,eps=1e-10):
"""FUNCTION::COSINE_DISTANCE:
>- Returns: The cosine distance between two arrays."""
return np.dot(x,y)/(np.linalg.norm(x)*np.linalg.norm(y)+eps)
def chi2_distance(x,y,eps=1e-10):
"""FUNCTION::CHI2_DISTANCE:
>- Returns: The chi squared distance between two arrays.
Works well with histograms."""
return np.sum((np.power(np.subtract(x,y),2)/(np.add(x,y)+eps)),axis=-1)
def histogram_intersection(x,y):
"""FUNCTION::HISTOGRAM_INTERSECTION:
>- Returns: The histogram intersection between two arrays.
Works well with histograms."""
return np.sum(np.minimum(x,y),axis=-1)
def hellinger_kernel(x,y):
"""FUNCTION::HELLINGER_KERNEL:
>- Returns: The hellinger kernel between two arrays."""
return np.sum(np.sqrt(np.multiply(x,y)))
|
#!/usr/bin/env python3
"""
Main module of the Assembler for the Hack platform.
It uses the Parser, Code and SymbolTable classes to read a Hack assembly language source file (.asm)
and generate an executable file (.hack)
It works in three steps:
* An INITIALIZATION phase, in which the symbol table is generated, as well as the ROM and RAM counters foe symbols.
* A FIRST PASS in which it reads the file and adds all the lables to the symbol table.
* A SECOND PASS in which it goes through the source file line by line and translates every command
to a 16 bit binary value, adding to the symbol table every unknown variable that it encounters.
Author: Rafael Villegas
"""
import sys
from hack_parser import Parser
from hack_code import Code
from hack_symbol_table import SymbolTable
def main():
""" Executes the Hack Assembler """
# if there is no source file specified, terminate the program
if len(sys.argv) != 2:
bad_usage()
source_file = str(sys.argv[1])
# get the name of the file, so it can be used again when writing to the .hack file
# also, if the file to be parsed isn't a .asm file, terminate the execution
extention_index = source_file.find('.asm')
if source_file[extention_index:] != ".asm":
bad_usage()
file_name = source_file[0:extention_index]
# initialize symbol table
symbol_table = SymbolTable()
# initialize the rom and ram counters for the symbl table
rom_counter = 0
ram_counter = 16
# --------------------------------------------FIRST PASS---------------------------------------------------------
# create parser
parser = Parser(source_file)
# read the whole file
while parser.has_more_commands():
parser.advance()
if parser.command_type() == "L_COMMAND":
# get the symbol for the label
label_symbol = parser.symbol()
# check thtat the label is a valid simbol
if label_symbol[0].isnumeric():
print("ERROR: symbol [{}] is not a valid symbol!\n".format(label_symbol))
raise SyntaxError
# add the label to the table
symbol_table.addEntry(label_symbol, rom_counter)
else:
# if it finds an A or C instruction, add 1 to the rom counter
rom_counter += 1
# delete parser after the first pass, to be able to read the file again
del parser
# ---------------------------------------------SECOND PASS-------------------------------------------------------
# create parser and coder
parser = Parser(source_file)
coder = Code()
# list in which to store all the translated binary commands
binary_commands = []
# read the whole file
while parser.has_more_commands():
parser.advance()
# A-Command
if parser.command_type() == "A_COMMAND":
# get the symbol
variable_symbol = parser.symbol()
# if it is not a number,but rather a variable
if not variable_symbol[0].isdigit():
# if the variable is in the table, get itś addres, translate it to 16-bit binary and add it to the list of commands
if symbol_table.contains(variable_symbol):
variable_addres = symbol_table.get_address(variable_symbol)
binary_variable = "{:016b}".format(variable_addres)
binary_commands.append(binary_variable+"\n")
# if it is not in the table, add it and then translate; then add 1 to the ram counter.
# also add to the binary command list
else:
symbol_table.addEntry(variable_symbol, ram_counter)
binary_variable = "{:016b}".format(ram_counter)
binary_commands.append(binary_variable+"\n")
ram_counter += 1
# else if the symbol is a number, just translate it and add it to the list of commands
elif variable_symbol.isdigit():
binary_number = "{:016b}".format(int(variable_symbol))
binary_commands.append(binary_number+"\n")
else:
print("ERROR: symbol [{}] is not a valid symbol!\n".format(variable_symbol))
raise SyntaxError
# C-Command
elif parser.command_type() == "C_COMMAND":
# get dest, comp and jump mnemonics of the command
dest_mnemonic = parser.dest()
comp_mnemonic = parser.comp()
jump_mnemonic = parser.jump()
# get the binary representation of each mnemonic using the coder (Code class)
binary_dest = coder.dest(dest_mnemonic)
binary_comp = coder.comp(comp_mnemonic)
binary_jump = coder.jump(jump_mnemonic)
# merge the three parts into one, following the structure comp bits -> dest bits -> jump bits
full_binary_command = "111{0}{1}{2}".format(binary_comp, binary_dest, binary_jump)
# add to the list of commands
binary_commands.append(full_binary_command+"\n")
# delete parser because it is not needed anymore
# also because it opens a file and we need to open another one
del parser
# open the corresponding .hack file and write the commands to it, line by line
with open(file_name + ".hack", "w") as exectuable_file:
exectuable_file.writelines(binary_commands)
def bad_usage():
""" Funtion that manages a bad argument usage of the program, terminating it right away """
print("Usage: python3 hack_assembler.py <Source File>.asm")
sys.exit(-1)
if __name__ == "__main__":
main()
|
num=45
guess =int(input('Enter an integer: '))
if guess==num:
print('congratulations,you guessed it.')
print('(but you dont win prizes!)')
elif guess<num:
print('no it is a little higher than that')
else:
print('it is a little lower than that')
print('Done')
|
#! usr/bin/env/python
# -*- coding: utf-8 -*-
import logging
# def foo():
# r = some_function()
# if r == (-1):
# return (-1)
# return r
# def bar():
# r = foo()
# if r == (-1):
# print 'Error'
# else:
# pass
# try:
# bar()
# except StandardError, e:
# print 'error is ',e
# try:
# print 'try...'
# r = 10 / int('2')
# print 'result:', r
# except ValueError, e:
# print 'ValueError:', e
# except ZeroDivisionError, e:
# print 'ZeroDivisionError:', e
# else:
# print 'no error!'
# finally:
# print 'finally...'
# print 'END'
# def foo(s):
# return 10/s
# def bar(s):
# return foo(s)*2
# def main():
# bar('0')
# try:
# bar('a')
# except StandardError as e:
# print 'error is %s' % e
# finally:
# print 'END'
# class FooError(StandardError):
# pass
# def testFoo(s):
# n = int(s)
# if n == 0:
# raise FooError('invaild value:%s' % s)
# return 10/n
# print testFoo('0')
def foo(s):
n = int(s)
return 10 / n
def bar(s):
try:
foo(s) * 2
except ZeroDivisionError:
print 'Error'
raise ValueError('input error!')
def main():
bar(0)
main()
logging.basicConfig(level=logging.INFO)
|
def day3_2(data, slope):
cpt=1
for i in slope:
cpt*=day3_1(data,i[0],i[1])
return cpt
def day3_1(data,right,down):
cpt=0
i=0
j=0
while i < len(data):
if data[i][j] == '#':
cpt += 1
j+=right
if j >= len(data[i]):
j -= len(data[i])
i += down
return cpt
# main
if __name__ == '__main__':
fichier = open('input.txt', 'r')
linesDeMonFichier = fichier.readlines()
data = []
for i in linesDeMonFichier:
data = data + [list(i)[0:len(i)-1]]
tree = day3_2(data,[[1,1],[3,1],[5,1],[7,1],[1,2]])
print(tree)
|
class node:
def __init__(self,data):
self.data = data
self.next = None
class linkedlist:
def __init__(self):
self.head = None
def append(self,data):
new_node = node(data)
if self.head is None:
self.head = new_node
temp = self.head
while temp.next:
temp = temp.next
temp.next = new_node
def prointer(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next
def delete(self,key):
temp = self.head
pr = None
if temp and temp.data!=key:
pr = temp
temp = temp.next
if temp and temp.data==key:
self.head = temp.next
temp = None
return
pr.next = temp.next
temp = None
l1 = linkedlist()
l1.head = node(5)
l1.append(2)
l1.append(3)
l1.delete(10)
l1.prointer()
|
#!/usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author: sadscv
@time: 2019/03/15 21:12
@file: exam.py
@desc:
"""
from typing import Any, Tuple
class Exam(object):
def __init__(self, exam_id, num_students):
self.conflicting_exams = {}
self._id = exam_id
self.num_students = num_students
def get_num_students(self):
return self.num_students
@property
def id(self):
return self._id
@id.setter
def id(self, exam_id: int):
if exam_id >= 0:
self._id = exam_id
def add_conflicting_exams(self, eid: int, num_students=None) -> None:
"""
Add a new exam to this exam collisions set
if there wasn't any previous collision between this exam and eid,
then create a new row inside the collision set and set the number of
students involved in the collision to 1. Otherwise, increase the
old value by one.
:param num_students: number of students conflicted while adding that
exam
:param eid: the id of the exam we want to add to the conflicting
exams set
"""
if num_students:
self.conflicting_exams[eid] = 1
else:
num_stu_involved = 1
if eid in self.conflicting_exams:
num_stu_involved += self.conflicting_exams[eid]
self.conflicting_exams[eid] = num_stu_involved
def get_conflict_exam(self) -> dict:
"""
dict{eid:num_conflict}
:return:
"""
return self.conflicting_exams
def stu_involved_in_collision(self, exam_id: int) -> int:
"""
Get the number of students that are enrolled in both this exam and
'exam_id' exam.
:param exam_id: The exam we want to check the collision for.
:return: The number of students involved in the collision. If no
collision exist, return 0;
"""
if exam_id in self.conflicting_exams:
return self.conflicting_exams[exam_id]
return 0
def is_compatible(self, exam_id: int) -> bool:
"""
Tells if this exam is compatible(i.e. not conflicting) with Exam(
exam_id)
:param exam_id:
:return: T/F if the two exams are conflicting or not
"""
return exam_id not in self.conflicting_exams
def conflict_exam_size(self):
return len(self.conflicting_exams)
def compare_to(self, other: 'Exam') -> int:
"""
Todo update to __cmp__ or lt,gt etc.
:param other:
:return:
"""
return self.conflict_exam_size() - other.conflict_exam_size()
def __str__(self):
return "Ex" + self._id + " "
def __eq__(self, other: object) -> bool:
if type(other) == Exam:
return other.get_id() == self.id
return False
def __hash__(self):
"""
override __hash__ func to make sure when two Exam instance with
same id comparing (like exam1 == exam2)would return true.
:return:
"""
hashcode = 5
hashcode = 31 * hashcode + hash(self._id)
return hashcode
def __copy__(self):
# cls = self.__class__
# result = cls.__new__(cls)
# result.__dict__.update(self.__dict__)
clone = Exam(self.id, self.num_students)
for key, value in self.conflicting_exams.items():
clone.add_conflicting_exams(key)
clone.add_conflicting_exams(key, value)
return clone
|
def park_new_car(parking_lot, registration_no, colour):
if parking_lot is None:
return 'Parking lot not initialized'
else:
return parking_lot.park_new_car(registration_no, colour)
def car_departure(parking_lot, slot_number):
if parking_lot is None:
return 'Parking lot not initialized'
# Case when slot_number is not present in the parking lot
elif slot_number > parking_lot.get_parking_lot_size():
return 'No such parking lot'
else:
return parking_lot.car_departure(slot_number)
def get_status(parking_lot):
if parking_lot is None:
print('Parking lot not initialized')
return
res = parking_lot.get_status()
print("Slot No. Registration No Colour")
for s, r, c in res:
print("{:<12}{:<19}{}".format(s, r, c))
def get_registration_by_colour(parking_lot, colour):
if parking_lot is None:
return 'Parking lot not initialized'
res = parking_lot.registration_numbers_for_cars_with_colour(colour)
if len(res) == 0:
return "No {0} cars are parked".format(colour)
else:
return res
def get_slot_by_colour(parking_lot, colour):
if parking_lot is None:
return 'Parking lot not initialized'
res = parking_lot.slot_numbers_for_cars_with_colour(colour)
if len(res) == 0:
return "No {0} cars are parked".format(colour)
else:
return res
def get_slot_by_registration(parking_lot, registration_no):
if parking_lot is None:
return 'Parking lot not initialized'
else:
return parking_lot.slot_number_for_registration_number(registration_no)
|
#! /usr/bin/python
# -*- coding: iso-8859-15 -*-
from pylab import *
import matplotlib.pyplot as plt
# import matplotlib import *
import numpy as np
#definimos el periodo de la grafica
periodo = 2
#definimos el array dimensional
x = np.linspace(0, 10, 1000)
#defimos la funcion
y = np.sin(2*np.pi*x/periodo)
#creamos la figura
plt.figure()
#primer grafico
plt.subplot(2,2,1)
plt.plot(x, y, 'r', linestyle=":")
#segundo grafico
plt.subplot(2,2,2)
plt.plot(x, y, 'g', linestyle="--")
#tercer grafico
plt.subplot(2,2,3)
plt.plot(x, y, 'B', linestyle=":")
#cuarto grafica
plt.subplot(2,2,4)
plt.plot(x, y, 'k', linestyle="--")
#mostramos en pantalla
plt.show()
|
#!/usr/bin/python3
"""Unittest for max_integer([..])
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
"""run test with python3 -m unittest -v tests.6-max_integer_test"""
def test_module_docstring(self):
moduleDoc = __import__('6-max_integer').__doc__
self.assertTrue(len(moduleDoc) > 1)
def test_function_docstring(self):
functionDoc = __import__('6-max_integer').max_integer.__doc__
self.assertTrue(len(functionDoc) > 1)
def test_signed_ints_and_floats(self):
self.assertEqual(max_integer([0]), 0)
self.assertEqual(max_integer([1, 2, 3, 4]), 4)
self.assertEqual(max_integer([1, 2, 3, -4]), 3)
self.assertEqual(max_integer([-1.5, -2.5]), -1.5)
self.assertEqual(max_integer([10, -10, 10]), 10)
self.assertEqual(max_integer([{1, 9}, {2}, {3}]), {1, 9})
def test_list_of_strings(self):
self.assertEqual(max_integer("6789"), '9')
self.assertEqual(max_integer("abcxyz"), 'z')
self.assertEqual(max_integer(['a', 'b', 'c', 'x', 'y', 'z']), 'z')
self.assertEqual(max_integer(["abc", 'x']), 'x')
def test_lists(self):
self.assertEqual(max_integer([[1, 2], [1, 3]]), [1, 3])
def test_other_sequences(self):
with self.assertRaises(TypeError):
max_integer({1, 2}, {3, 4, 5})
with self.assertRaises(TypeError):
max_integer({1, 2, 3, 4, 5})
with self.assertRaises(TypeError):
max_integer([-10, 0.5, "str", {1, 2}])
with self.assertRaises(TypeError):
max_integer([None, True])
def test_None(self):
self.assertIsNone(max_integer([]), None)
self.assertIsNone(max_integer(), None)
self.assertIsNone(max_integer([None]), None)
if __name__ == "__main__":
unittest.main()
|
#!/usr/bin/python3
"""
Module 0-read_file
Contains function that reads and prints contents from file
"""
def read_file(filename=""):
"""Read and print text from file"""
with open(filename, mode="r", encoding="utf-8") as f:
print(f.read(), end="")
|
#!/usr/bin/python3
"""
Module 5-text_indentation
Contains method that prints text with 2 new lines after each ".", "?", and ":"
Takes in a string
"""
def text_indentation(text):
"""
Prints text with 2 new lines after each ".", "?", and ":"
"""
if not isinstance(text, str):
raise TypeError("text must be a string")
for char in ".?:":
text = text.replace(char, char + "\n\n")
list_lines = [lines.strip(' ') for lines in text.split('\n')]
revised = "\n".join(list_lines)
print(revised, end="")
|
#!/usr/bin/python3
"""
given letter pattern as param to be search val of request; print Star War names
usage: ./101-starwars.py [letter pattern to match names]
"""
from sys import argv
import requests
if __name__ == '__main__':
if len(argv) < 2:
pattern = ""
else:
pattern = argv[1]
url = 'https://swapi.co/api/people/?search={}'.format(pattern)
r = requests.get(url)
print('Number of results: {}'.format(r.json().get('count')))
if r.json().get('count') > 0:
matching_names = r.json().get('results')
for person in matching_names:
print(person.get('name'))
more = r.json().get('next')
page = 2
while more is not None:
url = 'https://swapi.co/api/people/?search={}&page={}'.format(
pattern, page)
r = requests.get(url)
matching_names = r.json().get('results')
for person in matching_names:
print(person.get('name'))
more = r.json().get('next')
page += 1
|
NUM = int(input("enter: "))
for i in range(0,NUM+1):
for j in range(0,i+1):
print('*', end=" ")
print()
|
class Animal(object):
def __init__(self,name,color = "白色"):
self.name = name
self.color = color
def eat(self):
print("吃东西")
def setColor(self,color):
self.color = color
def __str__(self):
msg = "颜色是%s"%self.color
return msg
'''
子类没有init方法 但是父类有,当实例化对象的时候
默认执行init
'''
'''
私有属性和私有方法到底能不能被继承
不能继承的话 子类怎么间接获取私有属性和私有方法
'''
class Cat(Animal):
def uptree(self):
print("上树")
bosi = Cat("波斯猫","黑色")
bosi.uptree()
bosi.eat()
bosi.setColor("绿色")
print(bosi)
|
#10时间戳的获取方法
import time
t = time.time()
print(t)
print(int(t))
#13位时间戳的获取方法
import time
time.time()
#通过把秒转换毫秒的方法获得13位的时间戳
import time
millis = int(round(time.time() * 1000))
print millis
#round()是四舍五入
import time
current_milli_time = lambda: int(round(time.time() * 1000))
Then:
current_milli_time()
#13位时间 戳转换成时间
import time
now = int(round(time.time()*1000))
now02 = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(now/1000))
now02
|
sex=input('请输入你的性别:')
age=int(input('请输入你的年龄:'))
if sex=='男':
if age<=60:
print('继续努力')
else:
print('>60你该退休了')
else:
if age<=60:
pritn('继续努力')
else:
print('你该退休了')
|
a=int(input('请输入:'))
c=1
s=a
while c<=a:
print(' '*s , ' *'*c)
s=s-1
c=c+1
|
#型参 比喻成 盒子
#变量 比喻成 盒子
def add(a,b):
print(a)
print(b)
def add1(*anything):
print(anything)
def addsan(a,s,d):
a+s+d
def add_some(*num):
global re
for i in num:
re=i+re
print(num)
a=int(input(''))
add_some(1,10,20,30,40,50)
add_some(1,2,3,4,5,6)
#1到10的循环
a=0
for i in range(1,11):
a=a+i
print(a)
tup=(1,2,3,4,5)
a=0
for i in tup:
a=a+i
print(a)
a=1
a='a'
a=[1]
a={}
a=()
|
#写一个函数
#写三个数的和
#求三个数的平均数
def add(a,b,c):
return a+b+c
def pingjun(x,y,z):
g=add(x,y,z)
return g/3
def ji(z,w,e):
return z*w*e
f=ji(2,3,4)
print(f)
g=add(1,2,3)
print(g)
p=pingjun(2,4,6)
print(p)
|
name = input('请输入要备份的名字:')
f = open(name,'r')
a=name.rfind('.')
newname = name[:a]+"back"+name[a:]
newname=open(newname,'w')
q=f.read()
newname.write(q)
newname.close()
f.close()
|
'''
1='石头'
2='剪刀'
3='布'
'''
import random
qw=0
while qw < 10:
qw=qw+1
ef=int(input('请输入:'))
if ef==99:
break
pc=random.randint(1,3)
if ef==1:
print('吕布输出了石头')
elif ef==2:
print('吕布输出了剪刀')
else:
print('吕布输出了布')
if pc==1:
print('貂蝉输出了石头')
elif pc==2:
print('貂蝉输出了剪刀')
else:
print('貂蝉输出了布')
if (ef==1 and pc==2) or (ef==2 and pc==3) or (ef==3 and pc==3):
print('吕布赢了')
elif ef==pc:
print('平局')
else:
print('貂蝉赢了')
|
#coding=utf-8
#获取输入价格
price=float(input("请您输入西瓜的价格:"))
#获取输入重量
weight=float(input("请您输入西瓜的重量:"))
#把输入的str类型数据转化为float类型
#计算西瓜的总额
money=price*weight
print("该西瓜的单价是%.2f元"%(price))
print("该西瓜的重量是%.2f斤"%(weight))
print("该西瓜的总额是%.2f元"%(money))
|
'''
1=石头
2=剪刀
3=布
'''
import random
while True:
曹操=int(input('请出拳'))
刘备=random.randint(1,3)
print('曹操出%d'% 曹操)
print('刘备出%d'% 刘备)
if (曹操==1 and 刘备==2) or (曹操==2 and 刘备==3) or (曹操==3 and 刘备==1):
print('你真牛')
elif 曹操==刘备:
print('继续努力')
else:
print('你真菜')
|
import random
a= random.randint(1,100)
j=10
for i in range(j):
c=int(input('请输入数字'))
if a<c:
print('输入的太大')
elif a>c:
print ('你输入的太小')
else:
print('输入正确')
break
|
class Tudousi:
def __init__(self):
self.info='土豆丝'
self.lever=0
self.Seasoning=[]
def __str__(self):
for i in self.Seasoning:
self.info+=i+','
self.info=self.info.strip(',')
return '当前的土豆丝的状态是:%s,炒土豆丝使用了%d分钟'%(self.info,self.lever,)
def cook(self,t):
self.lever+=t
if self.lever>=15:
self.info='土豆丝炒糊了'
elif self.lever>=10:
self.info='土豆丝炒的刚刚好'
elif self.lever>=5:
self.info='土豆丝炒得半生不熟'
else:
self.info='土豆丝完全是生的'
def Add(self,Seasoning):
self.Seasoning.append(Seasoning)
tu=Tudousi()
print(tu.info)
tu.cook(10)
print(tu.info)
tu.Add('辣椒油')
tu.Add('油')
print(tu)
|
h=5
s=1
while h>0:
print(" "*h,"*"*s)
h=h-1
s=s+2
|
l = []
i = 0
while i < 100:
i += 1
if i%3 == 0 and i%5 == 0:
l.append(i)
print(l)
|
class Father(object):
a=None
def __init__(self,name):
self.name=name
def wan(self):
print('玩的很开心')
def __new__(cls,*a):
if cls.a == None:
cls.a = object.__new__(cls)
return cls.a
xiao=Father('小明')
print(id(xiao))
print(xiao.name)
hua=Father('小花')
print(id(hua))
print(hua.name)
|
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def set_width(self, width):
self.width = width
def set_height(self, height):
self.height = height
def get_area(self):
area = self.width * self.height
return area
def get_perimeter(self):
perimeter = 2 * self.width + 2 * self.height
return perimeter
def get_diagonal(self):
diagonal = (self.width ** 2 + self.height ** 2) ** .5
return diagonal
def get_picture(self):
if self.width > 50 or self.height > 50:
row = "Too big for picture."
else:
line = self.width * "*"
x = 0
row = ""
while x < self.height:
row += line + "\n"
x += 1
return row
def get_amount_inside(self, side):
number_of_times = (self.width * self.height) // (side.width * side.height)
return number_of_times
def __str__(self):
output = f"Rectangle(width={self.width}, height={self.height})"
return output
class Square(Rectangle):
def __init__(self, side):
self.width = side
self.height = side
def set_side(self, side):
self.width = side
self.height = side
def __str__(self):
output = f"Square(side={self.width})"
return output
|
#coding: utf8
def get_data_by_binary_search(target, source_list):
min=0
max=len(source_list)-1
while min<=max:
mid=(min+max)//2
if source_list[mid]==target:
return mid
if source_list[mid]>target:
max=mid-1
else:
min=mid+1
if __name__=='__main__':
source_list=[1,3,5,7,9,10,12,14,15,18]
res=get_data_by_binary_search(14, source_list)
print(res)
|
# import the argv feature from module sys
from sys import argv
# unpack argv into 2 variables
script, filename = argv
# open a file
txt = open(filename)
print "Here's your file %r:" % filename
# read file
print txt.read()
print "Type the filename again:"
# get user input
file_again = raw_input("> ")
txt_again = open(file_again).read()
print txt_again
|
# Write classes for the following class hierarchy:
#
# [Vehicle]->[FlightVehicle]->[Starship]
# | |
# v v
# [GroundVehicle] [Airplane]
# | |
# v v
# [Car] [Motorcycle]
#
# Each class can simply "pass" for its body. The exercise is about setting up
# the hierarchy.
#
# e.g.
#
# class Whatever:
# pass
#
# Put a comment noting which class is the base class
# assignment down below
class Vehicle:
'''Base class, or Parent class.'''
pass
class GroundVehicle(Vehicle): # inherit from vehicle
pass
class Car(GroundVehicle): # car inherits from ground vehicle
pass
class Motorcycle(GroundVehicle): # motorcycle inherits from groundvehicle
pass
class FlightVehicle(Vehicle): # flightvehicles inherit from vehicle
pass
class Airplane(FlightVehicle): # airplane from flight vehicle
pass
class Starship(FlightVehicle): # GO SPACEX!!
pass
|
from datetime import datetime
from database import *
todos = []
def create_todo():
"""
Create a new todo.
"""
todo_title = input("Enter a new item: ")
new_todo = {
"id" : len(todos) + 1,
"title": todo_title,
"completed": False,
"date_added": datetime.now().strftime("%d/%m/%Y %H:%M:%S")
}
todos.append(new_todo)
def print_todos():
"""
Print all todos.
"""
if len(todos) == 0:
print("No todos for today.")
else:
for todo in todos:
print("----------------------")
print("{} - {} - Completed: {}".format(todo["id"], todo["title"], todo["completed"]))
print("----------------------")
print(todos)
def edit_todo(todo_id):
"""
Edit a todo.
"""
for todo in todos:
if todo["id"] == todo_id:
todo["title"] = input("Enter a new title: ")
else:
print("No todo found with that id.")
def mark_todo_completed(todo_id):
"""
Mark a todo as completed.
"""
for todo in todos:
if todo["id"] == todo_id:
todo["completed"] = True
else:
print("No todo found with that id.")
def delete_todo(todo_id):
"""
Delete a todo.
"""
for todo in todos:
if todo["id"] == todo_id:
todos.remove(todo)
break
else:
print("No todo found with that id.")
def print_menu():
"""
Print the menu.
"""
print("""
1. Create a new todo
2. Print all todos
3. Edit a todo
4. Mark a todo as completed
5. Delete a todo
6. Quit
""")
if __name__ == '__main__':
try:
while True:
print_menu()
choice = input("Enter your choice: ")
if choice == "1":
create_todo()
elif choice == "2":
print_todos()
elif choice == "3":
todo_id = int(input("Enter todo id: "))
edit_todo(todo_id)
elif choice == "4":
todo_id = int(input("Enter todo id: "))
mark_todo_completed(todo_id)
elif choice == "5":
todo_id = int(input("Enter todo id: "))
delete_todo(todo_id)
elif choice == "6":
print("Goodbye!")
break
else:
print("Invalid choice.")
except KeyboardInterrupt:
print("Exiting...")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.