text
stringlengths 37
1.41M
|
---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 4 12:41:14 2019
@author: bijayamanandhar
"""
# Isogram Matcher
# ------------------------------------------------------------------------------
# An isogram is a word with only unique, non-repeating letters. Given two isograms
# of the same length, return an array with two numbers indicating matches:
# the first number is the number of letters matched in both words at the same position,
# and the second is the number of letters matched in both words but not in the
# same position.
class Solution(object):
def isogram_matcher(self, word1, word2):
# x: number of matching chars and indices
# y: number of matching chars but unmatched indices
x, y = 0, 0
for i in range(len(word1)):
for j in range(len(word1)):
if word1[i] == word2[j]:
if i == j:
x += 1
else:
y += 1
return [x, y]
if __name__ == "__main__":
S = Solution()
examples = [
["ultrasonic", "ostracized"],
["cat", "car"],
["england", "denmark"],
["home", "dome"],
["gains", "snake"],
["gamble", "maples"],
]
for example in examples:
print(S.isogram_matcher(example[0], example[1]))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 3 20:26:47 2019
@author: bijayamanandhar
"""
'''
write a function, bubble_sort(arr),
that acts to sort an array in a bubble methodology.
'''
class Solution(object):
def bubble_sort(self, arr):
for i in range(len(arr) - 1):
for j in range(len(arr) - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
if __name__ == '__main__':
S = Solution()
arrays = [
[2, 9, 1, 5, 7],
[-2, 5, 0, 8, 10],
[90, -8, 0, 34, 74, -8]
]
for i in range(len(arrays)):
print(S.bubble_sort(arrays[i]))
print(' ')
print("Next function ...")
class Solution1(object):
def bubble_sort1(self, arr):
for i in range(len(arr)-1, 0, -1):
for j in range(i):
if arr[j] > arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
return arr
if __name__ == '__main__':
S = Solution1()
arrays = [
[-9, 9, 1, 8, 6],
[3, 11, -1, 8, 6],
[100, -11, 90, 34, 74, -11]
]
for i in range(len(arrays)):
print(S.bubble_sort1(arrays[i]))
|
# Adapted from https://machinelearningmastery.com/implement-decision-tree-algorithm-scratch-python/
from csv import reader
import os
import numpy as np
import pandas as pd
LEFT = 'LEFT'
RIGHT = 'RIGHT'
def load_data(file_name):
instances = []
for line in open(os.path.join(os.path.dirname(__file__), file_name)):
tokens = line.split()
label = tokens[0]
line = line[2:]
tokens = line.split(' ')
features = np.zeros(17)
for feature in tokens:
feature_split = feature.split(':')
index = int(feature_split[0]) - 1
value = float(feature_split[1])
features[index] = value
features[-1] = label
instances.append(features)
return instances
def load_ids(file_name):
ids = []
for line in open(os.path.join(os.path.dirname(__file__), file_name)):
ids.append(line)
return ids
def score(actual, predicted):
correct = 0
for (y, prediction) in zip(actual, predicted):
if y == prediction:
correct = correct + 1
return correct / float(len(actual)) * 100.0
def test_split(index, value, dataset):
left = list()
right = list()
for row in dataset:
if row[index] < value:
left.append(row)
else:
right.append(row)
return left, right
# Calculate the Gini index for a split dataset
def gini_index(groups, classes):
n_instances = float(sum([len(group) for group in groups]))
gini = 0.0
for group in groups:
size = float(len(group))
# avoid divide by zero
if size == 0:
continue
score = 0.0
for class_val in classes:
p = [row[-1] for row in group].count(class_val) / size
score += p * p
gini += (1.0 - score) * (size / n_instances)
return gini
def get_split(dataset):
class_values = list(set(row[-1] for row in dataset))
b_index, b_value, b_score, b_groups = 999, 999, 999, None
for index in range(len(dataset[0])-1):
for row in dataset:
groups = test_split(index, row[index], dataset)
gini = gini_index(groups, class_values)
if gini < b_score:
b_index, b_value, b_score, b_groups = index, row[index], gini, groups
return {'index':b_index, 'value':b_value, 'groups':b_groups}
def to_terminal(group):
outcomes = [row[-1] for row in group]
return max(set(outcomes), key=outcomes.count)
def split(node, max_depth, min_size, depth):
left, right = node['groups']
del(node['groups'])
if not left or not right:
node[LEFT] = node[RIGHT] = to_terminal(left + right)
return
if depth >= max_depth:
node[LEFT], node[RIGHT] = to_terminal(left), to_terminal(right)
return
if len(left) <= min_size:
node[LEFT] = to_terminal(left)
else:
node[LEFT] = get_split(left)
split(node[LEFT], max_depth, min_size, depth + 1)
if len(right) <= min_size:
node[RIGHT] = to_terminal(right)
else:
node[RIGHT] = get_split(right)
split(node[RIGHT], max_depth, min_size, depth + 1)
def build_tree(train, max_depth, min_size):
root = get_split(train)
split(root, max_depth, min_size, 1)
return root
def predict(node, row):
if row[node['index']] < node['value']:
if isinstance(node[LEFT], dict):
return predict(node[LEFT], row)
else:
return node[LEFT]
else:
if isinstance(node[RIGHT], dict):
return predict(node[RIGHT], row)
else:
return node[RIGHT]
def decision_tree(train, test, max_depth, min_size):
tree = build_tree(train, max_depth, min_size)
return([predict(tree, row) for row in test])
def main():
train_instances = load_data('data-splits/data.train')
test_instances = load_data('data-splits/data.test')
train_instances += test_instances
anon_instances = load_data('data-splits/data.eval.anon')
anon_ids = load_ids('data-splits/data.eval.id')
predictions = decision_tree(train_instances, anon_instances, 9, 8)
rows = []
for (anon_id, prediction) in zip(anon_ids, predictions):
rows.append([anon_id, prediction])
df = pd.DataFrame(rows)
df.to_csv("decision_tree_12_predictions.csv", header=['Id','Prediction'])
if __name__ == "__main__":
main()
|
# 1. Is their first name longer than their last name?
def firstLongerThanLast(first, last):
return len(first) > len(last)
# 2. Do they have a middle name?
# 3. Does their first name start and end with the same letter? (ie "Ada")
def endsWithFirstLetter(first):
first = first.lower()
return first[0] == first[-1]
# 4. Does their first name come alphabetically before their last name? (ie "Dan Klein" because "d" comes before "k")
def firstBeforeLast(first, last):
first = first.lower()
last = last.lower()
return first > last
# 5. Is the second letter of their first name a vowel (a,e,i,o,u)?
def secondLetterIsVowel(first):
first = first.lower()
if len(first) > 1:
return first[1] in 'aeiou'
return False
# 6. Is the number of letters in their last name even?
def lastNameEvenLength(last):
return len(last) % 2 == 0
# 7. Is the first letter in the last name a vowel?
def firstLetterIsVowel(last):
first = last.lower()
if len(last) > 1:
return first[0] in 'aeiou'
return False
# 8. Is the first name only an initial?
def firstIsOnlyInitial(first):
first.replace(".", "")
return len(first) == 1
# 9. Is the first letter of the middle name a vowel?
def firstLetterIsVowelMiddle(middle):
first = middle.lower()
if len(middle) > 1:
return middle[0] in 'aeiou'
return False
# 10. Is the entire length of the full name even?
def lengthEven(full_name):
return len(full_name) % 2 == 0
# 11. Does their last name start and end with the same letter? (ie "Ada")
def endsWithFirstLetterLast(last):
last = last.lower()
return last[0] == last[-1]
# 12. Beginning of first name and last name match
def matchFirstAndLast(first, last):
return first[0] == last[-1]
# 13. The first and last name both end with a vowel
def firstAndLastEndWithVowel(first, last):
return first[-1] in 'aeiou' and last[-1] in 'aeiou'
# 14. Last name over 8 characters
def longLastName(last):
return len(last) > 8
# 15. First name under 5 characters
def shortFirstName(first):
return 5 > len(first)
# 16. Both the first name and the middle name are only an initial
def firstAndMiddleAreInitial(first, middle):
return len(first) <= 2 and len(middle) <= 2
# 17. First and last have same length
def firstAndLastLength(first, last):
return len(first) == len(last)
# 18. Last is longer than both first and middle cobined
def lastNameWins(first, middle, last):
return len(last) > len(first) + len(middle)
# 19.
def shortFullName(full_name):
return len(full_name) <= 8
# Given a string it returns an array of 1's or 0's for features
def featureize(full_name):
tokens = full_name.split()
has_middle_name = len(tokens) == 3
first_name = tokens[0]
if has_middle_name:
middle_name = tokens[1]
last_name = tokens[-1]
else:
last_name = tokens[1]
middle_name = ''
features = [firstLongerThanLast(first_name, last_name), has_middle_name, endsWithFirstLetter(first_name),
firstBeforeLast(first_name ,last_name), secondLetterIsVowel(first_name), lastNameEvenLength(last_name),
firstLetterIsVowel(last_name), firstIsOnlyInitial(first_name), firstLetterIsVowelMiddle(middle_name),
lengthEven(full_name), endsWithFirstLetterLast(last_name), matchFirstAndLast(first_name, last_name),
firstAndLastEndWithVowel(first_name, last_name), longLastName(last_name), shortFirstName(first_name),
firstAndMiddleAreInitial(first_name, middle_name), firstAndLastLength(first_name, last_name),
lastNameWins(first_name, middle_name, last_name), shortFullName(full_name)]
features = map(lambda x: 1 if x else 0, features)
return features
|
# Nick Porter, CS 4964 - Math for Data HW 4, Q1 (a), University of Utah
import pandas as pandas
import statsmodels.api as sm
import numpy as np
# Load the data
x = pandas.read_csv('D4.csv', usecols = [0,1,2])
y = pandas.read_csv('D4.csv', usecols = [3])
def batch_gradient_descent(learning_rate, iterations, x, y):
x = x.as_matrix()
y = y.as_matrix()
alphas = np.zeros(4)
for i in range(1, iterations):
gradient = np.zeros(4)
total_hypo = 0
total_cost = 0
# Compute the gradient for all data points
for data_point in range(0, 149):
hypothesis = evaluate(x[data_point], alphas)
# x_i - y
loss = hypothesis - y[data_point]
cost = loss**2
total_hypo += hypothesis
total_cost += cost
temp_gradient = np.zeros(4)
temp_gradient[0] = loss
temp_gradient[1] = loss * x[data_point][0]
temp_gradient[2] = loss * x[data_point][1]**2
temp_gradient[3] = loss * x[data_point][2]**3
gradient += temp_gradient
gradient *= 2
alphas = alphas - learning_rate * gradient
print("Iteration %d | Average f(x): %f" % (i, total_hypo/149))
print("Iteration %d | Average Cost: %f" % (i, total_cost/149))
print("Iteration %d | Alpha: %s" % (i, alphas))
def evaluate(x, alphas):
return alphas[0] + (alphas[1] * x[0]) + (alphas[2] * x[1]) + (alphas[3] * x[2])
batch_gradient_descent(0.00003, 15, x, y)
|
"""
load the given var from the given config
file and print. Allows us to decouple some
processing scripts from the config file by
loading the needed params into shell vars
via:
VAL = $(python getparam.py myfile.conf myvar)
"""
import argparse
from configobj import ConfigObj
def getparam(filename, varname, default=None):
try:
cfg = ConfigObj(filename, encoding='UTF8')
value = cfg[varname]
return value
except KeyError as e:
if default is not None:
return default
else:
raise
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='extract and print config var from file')
parser.add_argument('config_file')
parser.add_argument('var_name')
parser.add_argument('--default')
args = parser.parse_args()
value = getparam(args.config_file, args.var_name, args.default)
print(value)
|
def isPP(n):
for num in range (2, n//2 + 1):
number = n
count = 0
while number % num == 0:
count += 1
number /= num
if number == 1:
return [num, count]
else:
return None
|
n = 0
while n < 10 :
print("我想看看有几行")
n = n + 1
print('END')
|
#map() 处理序列中的每一个元素,得到的结果是一个‘列表’,该‘列表’元素个数及位置与原来的一样
#filter() 遍历序列中的每一个元素,判断每个元素得到布尔值,如果是True则留下来
people = [
{'name': 'alex', 'age': 1000},
{'name': 'wupei', 'age': 10000},
{'name': 'yuanhao', 'age': 9000},
{'name': 'RNG', 'age': 18}
]
res = list(filter(lambda p:p['age']<=18,people))
print(res)
#reduce:处理一个序列,然后把序列进行合并操作
from functools import reduce
print(reduce(lambda x,y:x+y,range(0,100),100))
print(reduce(lambda x,y:x+y,range(0,101)))
|
#生成器总结
#1.语法上和函数类似:生成器函数和常规函数几乎是一样的。它们都是使用def语句进行定义,差别在于
#生成器使用yield语句返回一个值,而常规函数使用return语句返回一个值
#2.自动实现迭代器协议:对于生成器,python会自动实现迭代器协议,以便应用到迭代背景中(如for循环,sum函数)。
#由于生成器自动实现了迭代器协议,所以,我们可以调用它的next方法,并且,在没有值可以返回的时候,生成器自动产生Stoplteration异常
#3.状态挂起:生成器使用yield语句返回一个值。yield语句挂起该生成器函数的状态,保留足够的信息,以便之后从它离开的地方继续执行
#优点一:生成器的好处是延迟计算,一次返回一个结果。也就是说,它不会一次产生所有的结果,这对于大数据量处理,将会非常有用
#优点二:生成器还能有效提高代码可读性
#这里,至少有两个充分的理由说明,使用生成器比不使用生成器代码更加清晰:
#1.使用生成器以后,代码行数更少。大家要记住,如果想把代码写的pythonic,在保证代码可读性的前提下,代码行数越少越好
#2.不使用生成器的时候,对于每次结果,我们首先看到的是result.append(index),其次,才是index。也就是说。
#我们每次看到的是一个列表的append操作,只是append的是我们想要的结果。使用生成器的时候,直接yield index,
#少了列表append操作的干扰,我们一眼就能够看出,代码是要返回index
#这个例子充分说明了,合理使用生成器,能够有效提高代码可读性。只要大家完全接受了生成器的概念,理解了yield语句和return语句一样,
#也是返回一个值。那么,就能够理解为什么使用生成器比不使用生成器要好,能够理解使用生成器真的可以让代码变得清晰易懂
#注意事项:生成器只能遍历一次(母鸡一生只能下一定数量的蛋,下完了就die了)
|
s = set('hello')
print(s)
s1 = set(['alex','alex','sb'])
print(s1)
#添加 只能添加一个值
s3 = {1,2,3,4,5,6}
s3.add('s')
s3.add('3')
s3.add(3)
print(s3)
#清空
# s3.clear()
# print(s3)
#拷贝
s9 = s3.copy()
print(s9)
#随机删除
s12 = {'s',1,2,3,4,5,6}
s12.pop()
print(s12)
#指定删除
s13 = {'sb',1,2,3,4,5,6}
s13.remove('sb') ##删除元素不存在会报错
print(s13)
#指定删除1.0
s14 = {'sbbbbb',1,2,3,4,5,6}
s14.discard('sbbbbb') #删除元素不存在不会报错
print(s14)
|
########### 灰魔法 ###########
#len() for循环 索引 切片 在其他数据类几乎都能用
test = "alex"
#索引,下标,获取字符串中的某一个字符
h = test[0]
print(h)
#切片
#索引范围 0=< <1
h1 = test[0:1]
print(h1)
#获取当前字符串中有几个字符组成
h2 = len(test)
print(h2)
#len 和 join 括号里除可以加字符串 还可以加入 列表
lie = [111,222,545456,548,8,18,18,1,855,18,]
h3 = len(lie)
print(h3)
#插入
h4 = " ".join("oskajdojsaod")
print(h4)
wen = "人生于世上有多少知己"
index = 0
while index < len(wen) :
v = wen[index]
print(v)
index += 1
#for 循环
# for 变量名 in 字符串:
# 变量名
for zzz in wen :
print(zzz )
|
n = 0
while n < 33 :
if n % 2 == 0 :
print('这是偶数')
n = n + 1
else :
break
#break 直接跳出循环
print('END')
|
# in 与 not in 不等于 != <> 等于 ==
# 结果:布尔值 大于等于 >= 小于等于 <=
name = "哈哈哈"
v = "哈" in name
print(v)
if v :
print("66666666666")
else :
print("888888888888888")
t = 1==1
print(t)
#测试 and 的 用法 一假即都假
if 1==1 and 2==2 :
print("真")
else :
print("假")
#测试 or 的 用法 一真即都真
if 1==1 or 2==3 :
print("真")
else :
print("假")
#补充: 如果多个判断的时候,先判断括号里面的
if 1==1 and (2==2 or 3==3) :
print("真")
else :
print("假")
#补充 如果没有括号的话,先判断第一个然后 与 and 或 or 比较
#例如: 如果第一个and 前面是真 那么还要继续判断后面 ,如果第一个and前面是假 那么就不用再判断了,因为这整个值都是假的
#or 同理
if 1==1 and 2==2 or 3==3 and 4==4 :
print("真")
else :
print("假")
|
# Given a Python list, find value 20 in the list, and if it is present, replace it with 200. Only update the first occurrence of a value
# Solution: https://github.com/JhonesBR
list1 = [5, 10, 15, 20, 25, 50, 20]
list1[list1.index(20)] = 200
print(list1)
|
# Format the following data using a string.format() method
# Given:
# totalMoney = 1000
# quantity = 3
# price = 450
# Expected Output:
# I have 1000 dollars so I can buy 3 football for 450.00 dollars.
# Solution: https://github.com/JhonesBR
totalMoney = 1000
quantity = 3
price = 450
print("I have {} so I can buy {} football for {:.2f} dollars.".format(totalMoney, quantity, float(price)))
|
# 10: Given an input string, count occurrences of all characters within a string
# Solution: https://github.com/JhonesBR
def countLetters(s):
letters = {}
for c in s:
if c not in letters:
letters[c] = s.count(c)
return letters
s = "Apple"
print(countLetters(s))
|
# Given a number count the total number of digits in a number
# Solution: https://github.com/JhonesBR
def numberOfDigits(n):
print(f"{n} has {len(str(n))} digits")
n = int(input("Insert a number: "))
numberOfDigits(n)
|
# Assign a different name to function and call it through the new name
# Solution: https://github.com/JhonesBR
def func(name, age):
print(f"Name: {name}\nAge: {age}")
func("Jhones", "19")
newFunc = func
newFunc("Jhones", "19")
|
# Find all occurrences of “USA” in a given string ignoring the case
# Solution: https://github.com/JhonesBR
def countUSA(s):
count = s.lower().count("usa")
print(f"The USA count is: {count}")
countUSA("Welcome to USA. usa awesome, isn't it?")
|
# Given a two Python list. Iterate both lists simultaneously such that list1
# should display item in original order and list2 in reverse order
# Solution: https://github.com/JhonesBR
def func(l1, l2):
for i in range(len(l1)):
print(l1[i], l2[len(l2)-1-i])
list1 = [10, 20, 30, 40]
list2 = [100, 200, 300, 400]
func(list1, list2)
|
# Given a nested list extend it by adding the sub list ["h", "i", "j"] in such a way that it will look like the following list
# list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
# Expected = ['a', 'b', ['c', ['d', 'e', ['f', 'g', 'h', 'i', 'j'], 'k'], 'l'], 'm', 'n']
# Solution: https://github.com/JhonesBR
list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
list1[2][1][2].extend(["h", "i", "j"])
print(list1)
|
# Accept two numbers from the user and calculate multiplication
# Solution: https://github.com/JhonesBR
n1 = int(input("First number: "))
n2 = int(input("Second number: "))
print(f"{n1} * {n2} = {n1*n2}")
|
# Count all lower case, upper case, digits, and special symbols from a given string
# Solution: https://github.com/JhonesBR
def countCDS(s):
chars, digits, symbols = 0, 0, 0
for c in s:
if c.isdigit():
digits += 1
else:
if c.isalpha():
chars += 1
else:
symbols += 1
print("Chars =", chars)
print("Digits =", digits)
print("Symbols =", symbols)
s = "P@#yn26at^&i5ve"
countCDS(s)
|
# String characters balance Test
# We’ll assume that a String s1 and s2 is balanced if all the chars in the s1 are there in s2. characters’ position doesn’t matter.
# Solution: https://github.com/JhonesBR
def balance(s1, s2):
for c in s1:
if not c in s2:
return False
return True
print(balance("Yn", "PYnative"))
print(balance("Ynf", "PYnative"))
|
# Find the last position of a substring “Emma” in a given string
# Solution: https://github.com/JhonesBR
def lastEmmaOccurence(s):
return s.rfind("Emma")
s = "Emma is a data scientist who knows Python. Emma works at google."
print("Last occurrence of Emma starts at", lastEmmaOccurence(s))
|
# Initialize dictionary with default values
# Solution: https://github.com/JhonesBR
employees = ['Kelly', 'Emma', 'John']
defaults = {"designation": 'Application Developer', "salary": 8000}
final = dict.fromkeys(employees, defaults)
print(final)
|
# Iterate a given list and count the occurrence of each element and create a dictionary to show the count of each element
# Solution: https://github.com/JhonesBR
def countElements(L):
elements = {}
for c in L:
if c not in elements:
elements[c] = L.count(c)
return elements
L = [11, 45, 8, 11, 23, 45, 23, 45, 89]
print(countElements(L))
|
# Write a function called "exponent(base, exp)" that returns an int value of base raises to the power of exp.
# Solution: https://github.com/JhonesBR
def exponent(base, exp):
print(f"{base} raises to the power of {exp} is: {base**exp}")
base = int(input())
exp = int(input())
exponent(base, exp)
|
# Display numbers from -10 to -1 using for loop
# Solution: https://github.com/JhonesBR
for i in range(-10, 0):
print(i)
|
x=int(input('enter height in feet '))
y=int(input('enter height in inches '))
z=x*12
print(z)
p=y+z
print(p)
h=p*2.54
print(h)
print('the height of person is ',h)
|
## leetcode 37
## 解数独
## 基于第36题,加入回溯
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
def is_available(row, col, box, num):
box_index = (row // 3) * 3 + col//3
return not (row_map[row][num] or col_map[col][num] or box_map[box_index][num])
def insert_num(row, col, box, num):
row_map[row][num] = True
col_map[col][num] = True
box_map[box][num] = True
board[row][col] = str(num)
def remove_num(row, col, box, num):
row_map[row][num] = False
col_map[col][num] = False
box_map[box][num] = False
board[row][col] = '.'
def add_next(row, col):
if row == 8 and col == 8:
nonlocal solved
solved = True
elif col == 8:
backtrack(row + 1, 0)
else:
backtrack(row, col + 1)
def backtrack(row=0, col=0):
if board[row][col] == '.':
box_idx = (row // 3) * 3 + (col // 3)
for num in range(1,10,1):
if is_available(row, col, box_idx, num):
insert_num(row, col, box_idx, num)
add_next(row, col)
if not solved:
remove_num(row, col, box_id, num)
else:
add_next(row, col)
row_map = [[False for _ in range(1,10) ] for _ in range(9)]
col_map = [[False for _ in range(1,10) ] for _ in range(9)]
box_map = [[False for _ in range(10)] for _ in range(9)]
for ii in range(9):
for jj in range(9):
box_id = (ii // 3) * 3 + (jj // 3)
if board[ii][jj] != '.':
dd = int(board[ii][jj])
insert_num(dd,ii,jj,box_id)
solved = False
backtrack()
|
## leetcode 1036
## 解数独
## 思路是利用map,并且定义行、列、格子的map list
class Solution:
## def isValidSudoku(self, board: List[List[str]]) -> bool:
def isValidSudoku(self, board):
# init three maps
row_map = [ [False for _ in range(10)] for _ in range(9)]
col_map = [ [False for _ in range(10)] for _ in range(9)]
box_map = [ [False for _ in range(10)] for _ in range(9)]
# validate
for ii in range(9):
for jj in range(9):
if board[ii][jj] != '.':
num = int(board[ii][jj])
box_id = (ii//3) * 3 + jj//3
if (row_map[ii][num] or col_map[jj][num] or box_map[box_id][num]):
return False
else:
row_map[ii][num] == True
col_map[jj][num] == True
box_map[box_id][num] = True
return True
if __name__ == '__main__':
s = Solution()
board = [
["8","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
print(s.isValidSudoku(board))
|
user_1=str(input("give an input: "))
user_2=str(input("give an input: "))
a=["rock","scissors","paper"]
if user_1==user_2:
print("restart the game")
elif user_1=="rock" and user_2 =="scissors" :
print("user_1 won the match")
elif user_1=="scissors" and user_2=="paper":
print("user_1 won the match")
elif user_1=="paper" and user_2=="rock":
print("user_1 won the match")
else :
print("user_2 won the match")
|
# This is where Exercise 5.4 goes
# Name: Brendan Gassler
def is_triangle(a, b, c):
if a > b + c:
print "No"
elif b > a + c:
print "No"
elif c > a + b:
print "No"
else:
print "Yes"
a = raw_input('What length is the first leg?\n')
b = raw_input('What length is the second leg?\n')
c = raw_input('What length is the third leg?\n')
is_triangle(a, b, c)
|
count = "123456"
secret = "abcdefg"
print(count, secret)
price = 4.5
weight = 2
sumPrice = price * weight
print(sumPrice)
# type(sumPrice) 查看类型
print(type(sumPrice))
# 字符串 + 连接 可以拼接
firstName = "Dosen"
lastName = "Jack"
print(lastName + " " + firstName)
mm = input("请输入银行密码(6位数字)") # input("提示语相当于placeholder") 得到的一定是字符串 可以通过转换得到整数or浮点数
print(mm)
|
import turtle #导入海龟包
import time #导入时间包
turtle.speed(1) #设置指针速度为9(范围1-10)(不重要)
x = 300 #设置三角形初始边长
turtle.left(120) #因为画图指针初始为沿着x轴正向的,所以设置指针左转120°
for j in range(6): #for循环.range(x,y-1)相当于一个从x到y的数组(只有一个数就是从零开始)
#相当于给j赋值,从x到y-1.循环y-x次
for i in range(3): #循环3次
turtle.forward(x) #指针向前移动X的距离
turtle.left(120) #指针左转向120°
x = x/2 #上面的循环画出了打的三角形,下个三角形的边长为上个三角形的一半.
turtle.forward(x) #沿着边移动到大三角形边的中点
turtle.left(60) #指针左转60°这步转向是为了调整小三角形初始画线的方向,
time.sleep(5) #画完后延迟5秒关闭窗口(不重要)
# import turtle as t
# import time
# t.color("red", "yellow")
# t.speed(10)
# t.begin_fill()
# for _ in range(50):
# t.forward(200)
# t.left(170)
# turtle.end_fill()
# time.sleep(5)
|
s = input()
s1 = ''
for el in s:
if el.isalpha():
if el == 'z' or el == 'Z':
el = chr(ord(el)-25)
else:
el = chr(ord(el)+1)
s1 += el
print(s1)
#字符串编码
|
#teams = ["Packers", "49ers", "Ravens", "Patriots"]
#print({key: value for value, key in enumerate(teams)})
# print(','.join(teams))
# data = {'user': 1, 'name': 'Max', 'three': 4}
# is_admin = data.get('user', False)
# print(is_admin)
#
# for x in range(1,101):
# print("fizz"[x % 3*4::]+"buzz"[x % 5*4::]or x)
# from collections import Counter
# print(Counter("hello"))
# lst = []
# for i in range(1, 31):
# lst.append('*'[i % 3::] or i)
# print(lst)
# print([(x, y) for x in range(10) if x % 2 if x > 3 for y in range(10) if y > 7 if y != 8])
# for x in range(10):
# if x % 2:
# print(x)
# lst = [1, 5, 6, 5, 7, 2, 9]
# for el in range(len(lst)):
# lst.pop()
# print(lst)
# lst = ['周星驰', '周杰伦', '周润发', '马云', '周树人']
# dele = []
# for el in lst:
# if "周" in el:
# dele.append(el)
# for el in dele:
# lst.remove(el)
# print(lst)
i = 0
a = [12, 2, 5, 23, 56, 1, 52, 24]
for j in range(len(a)-1, 0, -1):
i = 0
while i < j:
if a[i] > a[i+1]:
a[i], a[i+1] = a[i+1], a[i]
i += 1
print(a)
|
'''迭代器'''
class Fibs:
'''这是doc'''
def __init__(self):
print('init')
self.a = 0
self.b = 1
def __next__(self):
print('next')
self.a,self.b = self.b, self.a+self.b
return self.a
def __iter__(self):
print('iter')
return self
|
import streamlit as st
import pandas as pd
from PIL import Image
st.write("""
# Stock Market Web Application
**Visually** show data on a stock! Data range From NOV 11,2020 - NOV 11, 2021
""")
image = Image.open("Stock.jpg")
st.image(image, use_column_width= True)
st.sidebar.header('User Input')
def get_input():
start_date = st.sidebar.text_input ("Start Date", "2020-11-11")
end_date = st.sidebar.text_input("End_Date", "2021-11-10")
stock_symbol = st.sidebar.text_input("Stock Symbol", "AMZN")
return start_date, end_date, stock_symbol
def get_comapny_name(symbol):
if symbol == "AMZN":
return 'Amazon'
elif symbol == "TSLA":
return 'Tesla'
elif symbol == "GOOG":
return 'ALphabet'
else:
'NONE'
def get_data(symbol, start, end):
if symbol.upper() =='AMZN':
df = pd.read_csv("AMZN.csv")
elif symbol.upper() == 'TSLA':
df = pd.read_csv("TSLA.csv")
elif symbol.upper() == 'GOOG':
df = pd.read_csv("GOOG.csv")
else:
df= pd.DataFrame(columns={'Date','Open','High','Low','Close','Adj Close','Volume'})
start = pd.to_datetime(start)
end = pd.to_datetime(end)
start_row = 0
end_row = 0
for i in range (0, len(df)):
if start <= pd.to_datetime(df['Date'][i] ):
start_row = i
break
for j in range (0, len(df)):
if end >= pd.to_datetime(df['Date'][len(df)-1-j]):
end_row = len(df)-1-j
break
df = df.set_index(pd.DatetimeIndex(df['Date'].values))
return df. iloc[start_row:end_row +1, :]
start, end, symbol = get_input()
df= get_data(symbol, start, end)
company_name = get_comapny_name(symbol.upper())
st.header(company_name+" Close price\n")
st.line_chart(df['Volume'])
st.header('Data Statistics')
st.write(df.describe())
|
import csv
from itertools import groupby
def csv_to_dict(csv_file):
data = []
with open(csv_file) as fin:
reader = csv.reader(fin, skipinitialspace=True, quotechar="'")
for keys in reader: break
for row in reader:
data.append(dict(zip(keys, row)))
return data
def keep_entries(list_of_dicts, keys_to_keep):
out = []
for row in list_of_dicts:
out.append({
key: row[key] for key in keys_to_keep
})
return out
def group_by_key(list_of_dicts, key):
out = {}
for k, values in groupby(list_of_dicts, key=lambda x:x[key]):
out[k] = [list(x.values())[:-1] for x in values] # assumes the key is last
return out
def unique_members_from_columns(list_of_dicts, keys):
out = []
for row in list_of_dicts:
for key in keys:
out.append(row[key])
return list(set(out))
|
##In this project, we're doing a Dice!
#Frist, we need to import something random. So,
import random
#Now, we need to create a variable and give it the random value.
dice=random.randint(1,6)
#The 1,6 is the minimum and maximum.
#We already have a dice. Now we just need to print the variable if we wanna see the number.
print (dice)
#Now, if we run it, we'll get a random number between 1 and 6.
#I don't know why, but the frist 3 times I ran the code, I got 1.
|
y=0
x="deez nuts "
while y == 0:
print (x)
x=x+x
|
#(not important)
space=" "
###This is a guide about loops in Phyton
##There's two types of loops in python, for and while
##For
primes = [2, 3, 5, 7]
for prime in primes:
print(prime) #(will print those numbers [2, 3, 5, 7])
print (space)
# Prints out the numbers 0,1,2,3,4
for x in range(5):
print(x) #(will print from 0 to 4)
print (space)
# Prints out 3,4,5
for x in range(3, 6):
print(x) #(will print from 3 to 5)
print (space)
# Prints out 3,5,7
for x in range(3, 8, 2):
print(x) #(I don't understand this one. Sorry.)
print (space)
print (space)
##Remenber, if the For time is used with Range, the Max won't count.
#(for example, 3 to 6, only 3; 4 and 5.)
##While
count = 0
while count < 5:
print(count)
count += 1 #(will print until it reachs 4)
|
x=int(input())
#While the number is greater 10 we keep going
while x>=10:
numbers = [int(i) for i in str(x)]
count = 1
for i in range(len(numbers)):
if numbers[i] != 0:
count = count * numbers[i]
x = count
print(x)
|
def mergeSort(inp_arr):
# current length of array
size = len(inp_arr)
if size > 1:
middle = size // 2
left_arr = inp_arr[:middle] #left half of the array
right_arr = inp_arr[middle:] #right half of the array
mergeSort(left_arr) #recursive call for the left half
mergeSort(right_arr) #recursive call for the right half
lp = rp = op = 0 #lp -> pointer for left array, rp -> pointer for right array
#op -> pointer for the original array
left_size = len(left_arr)
right_size = len(right_arr)
# compare elements from both left and right array and insert into original array
while lp < left_size and rp < right_size:
if left_arr[lp] < right_arr[rp]:
inp_arr[op] = left_arr[lp]
lp += 1
else:
inp_arr[op] = right_arr[rp]
rp += 1
op += 1
# if there are any elements left in left array, this loop will execute
while lp < left_size:
inp_arr[op] = left_arr[lp]
lp += 1
op += 1
# if there are any elements left in right array, this loop will execute
while rp < right_size:
inp_arr[op]=right_arr[rp]
rp += 1
op += 1
def main():
inp_arr = [11, 31, 7, 41, 101, 56, 77, 2]
print("Sample input: ", inp_arr) #Sample input: [11, 31, 7, 41, 101, 56, 77, 2]
mergeSort(inp_arr)
print("Sample output: ",inp_arr) #Sample output: [2, 7, 11, 31, 41, 56, 77, 101]
if __name__ == "__main__":
main()
|
import math
class GridIndex(object):
def __init__(self, size):
self.size = size
self.grid = {}
# Insert a point with data.
def insert(self, p, data):
self.insert_rect(p.bounds(), data)
# Insert a data with rectangle bounds.
def insert_rect(self, rect, data):
def f(cell):
if cell not in self.grid:
self.grid[cell] = []
self.grid[cell].append(data)
self.each_cell(rect, f)
def each_cell(self, rect, f):
for i in xrange(int(math.floor(rect.start.x / self.size)), int(math.floor(rect.end.x / self.size)) + 1):
for j in xrange(int(math.floor(rect.start.y / self.size)), int(math.floor(rect.end.y / self.size)) + 1):
f((i, j))
def search(self, rect):
matches = set()
def f(cell):
if cell not in self.grid:
return
for data in self.grid[cell]:
matches.add(data)
self.each_cell(rect, f)
return matches
|
str1 = "Hello World"
print(str1) #this is print value of str1
print(type(str1)) #this is print data type of str1
|
mark= int(input("Enter your mark: "))
if mark > 0 and mark <40:
print("F")
elif mark >= 40 and mark < 80:
if mark < 60:
print("P-")
else:
print("P+")
elif mark >= 80 and mark <=100:
print("D")
else:
print("Invalid")
|
import PIL #Importing Pillow library which can be used for image processing
from PIL import Image
from tkinter.filedialog import *
fp=askopenfilename() #Asks our filepath to be used
Image= PIL.Image.open(fp)
h,w=Image.size
image=Image.resize((h,w),PIL.Image.ANTIALIAS)
savingpath=asksaveasfilename()
image.save(savingpath+"Compressed.jpeg")
|
from math import sqrt
from random import randint, uniform
import math
# print(f'd = {d}')
a = randint(0, 100)
b = randint(0, 100)
c = randint(0, 100)
d = randint(0, 100)
print(a, b, c, d)
# 2.33. Возраст Тани – X лет, а возраст Мити – Y лет. Найти их средний возраст,
# а также определить, на сколько отличается возраст каждого ребенка от среднего значения.
v = (a + b) / 2
av = a - v
bv = b - v
#print(v, av, bv)
# 2.34. Два автомобиля едут навстречу друг другу с постоянными скоростями V1 и
# V2 км/ч. Определить, через какое время автомобили встретятся, если расстояние
# между ними было S км.
t = c / (a + b)
#print(t)
# 2.35. Два автомобиля едут друг за другом с постоянными скоростями V1 и V2 км/ч
# (V1 > V2). Определить, какое расстояние будет между ними через 30 мин после
# того, как первый автомобиль опередил второй на S км.
if a > b:
l = (a - b) * 0.5 + c
#print(l)
# 2.36. Известно значение температуры по шкале Цельсия. Найти соответствующее
# значение температуры по шкале:
# а) Фаренгейта;
# б) Кельвина.
# Для пересчета по шкале Фаренгейта необходимо исходное значение температуры
# умножить на 1,8 и к результату прибавить 32, а по шкале Кельвина абсолютное
# значение нуля соответствует –273,15 градуса по шкале Цельсия.
f = a * 1.8 + 32
k = a + -273.15
#print(f, k)
# 2.37. У американского писателя-фантаста Рэя Бредбери есть роман «450 градусов
# по Фаренгейту». Разработать программу, которая определяет, какой температуре
# по шкале Цельсия соответствует указанное в названии значение.
f = 450
cel = (f - 32) / 1.8
print(cel)
# 2.38. Напишите программу, в которой вычисляется сумма, разность, произведение,
# частное и среднее арифметическое двух целых чисел, введенных с клавиатуры.
# Например, при вводе чисел 2 и 7 должен быть получен ответ вида:
# 2+7=9 2-7=-5 2*7=14 2/7=0.2857142857142857 (2+7)/2=4.5
|
from random import randint
import time
'''
Игра моделирует бросание игрального кубика каждым из двух участников, после
чего определяется, у кого выпало больше очков.
В программе используем переменные:
player1 -
player2 -
n1 - digit of cube player1
n2 – digit of cube player2
s - points for win
i1 - total of points player1
i2 - total of points player2
• функция sleep() from module time, for made pause in work the programm
'''
s = 10
i1 = 0
i2 = 0
#Ввод имен играющих
player1 = input('What is your name? ')
player2 = input('What is your name? ')
#Моделирование бросания кубика первым играющим
for k in range(s):
print('Throw cube ', player1)
time.sleep(1)
n1 = randint(1, 6)
i1 += n1
print(' Points: ', n1)
#Моделирование бросания кубика вторым играющим
print('Throw cube', player2)
time.sleep(1)
n2 = randint(1, 6)
i2 += n2
print(' Points:', n2)
time.sleep(1)
print(player1,':',player2)
print('% 3d '% i1, '% 4d '% i2)
#Определение результата (3 возможных варианта)
if i1 > i2:
print('Winner', player1)
elif i1 < i2:
print('Winner', player2)
else:
print('Ничья')
|
from random import randint, uniform
import math
# print(f'd = {d}')
a = randint(0, 100)
b = randint(0, 100)
c = randint(0, 100)
d = randint(0, 100)
e = randint(0, 100)
f = randint(0, 100)
print(a, b, c, d, e, f)
# n = a
# for k in range(6): # отбросить последнюю цифру числа n
# n = n // 10
# print(n)
# n = a
# i = 0
# while n > 0: # количество цифр
# n = n // 10
# i += 1
# print(i)
# #Определение НОД
# while a != b:
# if a > b:
# a = a - b
# else:
# b = b - a
# НОД = a
# print('НОД равен', НОД)
# n = 10
# while n < 100:
# if n % 2 == 1:
# print(n,'', end='')
# n += 1
# n = a # сумма цифр натурального числа
# sum = 0
# while n > 0:
# dig = n % 10 # last number
# sum += dig
# n = n // 10
# print(sum)
# n = 10
# while n < 100:
# if n * n < a:
# print(n,'', end='')
# n += 1
# n = 1
# while n < 100:
# n += 1
# if n * n < a:
# print(n*n)
# while True:
# print('Задайте значение коэффициента а уравнения:')
# a = float(input())
# if a != 0:
# break # досрочный выход из цикла
# for <всех значений в наборе>:
# if <условие поиска значения> истинно:
# break
# ...
# while True:
# print('Задайте значение коэффициента а уравнения:')
# a = float(input())
# if 2 < a < 5:
# print('very good - welcome')
# break # досрочный выход из цикла
# elif a <= 2:
# print('too small number')
# elif a > 5:
# print('too big number')
# while True:
# print('enter password:')
# a = float(input())
# if a == 34567:
# print('very good - welcome!!!')
# break # досрочный выход из цикла
# else:
# print('get out, please!!!')
# while True:
# print('enter number:')
# a = float(input())
# if a == 0:
# print('game over')
# break # досрочный выход из цикла
# else:
# print('enter more numbers!!!')
# x = a
# while True:
# print('enter number:')
# y = int(input())
# if y * y > x:
# print('ok - correct')
# break # досрочный выход из цикла
# else:
# print('enter other number!!!')
|
from tkinter import *
from backend import database
db = database()
class interface:
def get_selection(self,event):
global selected_tuple
index = box.curselection()[0]
selected_tuple = box.get(index)
e1.delete(0,END)
e1.insert(END,selected_tuple[1])
e2.delete(0,END)
e2.insert(END,selected_tuple[2])
e3.delete(0,END)
e3.insert(END,selected_tuple[3])
e4.delete(0,END)
e4.insert(END,selected_tuple[4])
def viewall_command(self):
box.delete(0,END)
for row in db.view():
box.insert(END,row)
def search_record(self):
box.delete(0,END)
for row in db.search(title_text.get(),author_text.get(),year_text.get(),isbn_text.get()):
box.insert(END,row)
def add_record(self):
box.delete(0,END)
if db.search(isbn=isbn_text.get()) == []:
if(title_text.get() != ""):
db.insert(title_text.get(),author_text.get(),year_text.get(),isbn_text.get())
box.insert(END,(title_text.get(),author_text.get(),year_text.get(),isbn_text.get()))
else:
box.insert(END,"Enter a book name to add.")
else:
box.insert(END,"The isbn already exists.")
def update_record(self):
db.update(selected_tuple[0],title_text.get(),author_text.get(),year_text.get(),isbn_text.get())
box.delete(0,END)
box.insert(END,(title_text.get(),author_text.get(),year_text.get(),isbn_text.get()))
def delete_record(self):
db.delete(selected_tuple[0])
self.viewall_command()
interface=interface()
window = Tk()
l1 = Label(window,text="Title")
l1.grid(row=0,column=0)
l2 = Label(window,text="Author")
l2.grid(row=0,column=2)
l3 = Label(window,text="Year")
l3.grid(row=1,column=0)
l4 = Label(window,text="ISBN")
l4.grid(row=1,column=2)
title_text = StringVar()
e1 = Entry(window,textvariable=title_text)
e1.grid(row=0,column=1)
author_text = StringVar()
e2 = Entry(window,textvariable=author_text)
e2.grid(row=0,column=3)
year_text = StringVar()
e3 = Entry(window,textvariable=year_text)
e3.grid(row=1,column=1)
isbn_text = StringVar()
e4 = Entry(window,textvariable=isbn_text)
e4.grid(row=1,column=3)
box = Listbox(window,height=6,width=35)
box.grid(row=2,column=0,rowspan=6,columnspan=2)
box.bind('<<ListboxSelect>>',interface.get_selection)
scroll1 = Scrollbar(window)
scroll1.grid(row=2,column=2,rowspan=6)
box.configure(yscrollcommand=scroll1.set)
scroll1.configure(command=box.yview)
scroll2 = Scrollbar(window,orient="horizontal")
scroll2.grid(row=7,column=0,columnspan=2)
box.configure(xscrollcommand=scroll2.set)
scroll2.configure(command=box.xview)
b1 = Button(window,text="Search",width=13,command=interface.search_record)
b1.grid(row=2,column=3)
b2 = Button(window,text="Add",width=13,command=interface.add_record)
b2.grid(row=3,column=3)
b3 = Button(window,text="View All",width=13,command=interface.viewall_command)
b3.grid(row=4,column=3)
b4 = Button(window,text="Update",width=13,command=interface.update_record)
b4.grid(row=5,column=3)
b5 = Button(window,text="Delete",width=13,command=interface.delete_record)
b5.grid(row=6,column=3)
b6 = Button(window,text="Close",width=13,command=window.destroy)
b6.grid(row=7,column=3)
window.mainloop()
|
fname = input("Enter file: ")
if len(fname) < 1 : fname = 'clown.txt'
hand = open(fname)
di = dict()
for line in hand:
line = line.rstrip()
wds = line.split()
for w in wds:
#retrieve/create/update counter
di[w] = di.get(w,0) + 1
print(di)
largest = -1
theword = None
#the most common word
for k,v in di.items():
if v > largest:
largest = v
theword = k #/capture/remember the the largest word
print('Done',theword, largest)
|
__author__ = 'ubuntu'
import requests
import operator
from tabulate import tabulate
def get_data():
"""gets data from REST Countries, returns json"""
r = requests.get('https://restcountries.eu/rest/v1/all')
return r.json()
def get_currencies_data(r):
"""returns a dictioniary, keys (str) are currencies, values (int) are number of people using these currencies"""
currencies_data = {}
for country in r:
for currency in country['currencies']:
if currency in currencies_data:
currencies_data[currency] += int(country['population'])
else:
currencies_data[currency] = int(country['population'])
return currencies_data
def sort_data(data):
"""sorts a dictionary by its values, returns a tuple with tuples"""
sorted_data = sorted(data.items(), key=operator.itemgetter(1))
return tuple(reversed(sorted_data))
def pack_data(data, number_to_print):
"""returns data in pretty table, user sets how many records are printed"""
table = [["Place", "Currency", "Users [millions]"], ["-----", "--------", "----------------"]]
for index, item in enumerate(data):
if index < number_to_print:
table.append([index+1, item[0], round(item[1]/1000000,2)])
else:
break
return tabulate(table)
def save_data(data):
"""saves data to 'results.txt'"""
try:
with open('results.txt', 'w') as file:
file.write(data)
except IOError:
print("IOError!")
print(pack_data(sort_data(get_currencies_data(get_data())), 100))
save_data(pack_data(sort_data(get_currencies_data(get_data())), 100))
|
""" Linesorting """
def main(num, data):
""" Main Function """
for _ in range(num):
text = input()
data.append(text)
data.sort(key=len)
for i in data:
print(i)
main(int(input()), [])
|
def mergesort(arr):
if len(arr) <= 1:
return (arr)
middle = len(arr) // 2
left_arr = arr[:middle]
right_arr = arr[middle:]
left_arr = mergesort(left_arr)
right_arr = mergesort(right_arr)
return (merge(left_arr, right_arr))
def merge(left, right):
total_len_new_arr = len(left) + len(right)
new_arr = [0] * total_len_new_arr
i = 0
j = 0
pntr = 0
while i < len(left) and j < len(right):
if left[i] > right[j]:
new_arr[pntr] = right[j]
pntr += 1
j += 1
else:
new_arr[pntr] = left[i]
pntr += 1
i += 1
while i < len(left):
new_arr[pntr] = left[i]
pntr += 1
i += 1
while j < len(right):
new_arr[pntr] = right[j]
pntr += 1
j += 1
return (new_arr)
if __name__ == '__main__':
print('yo')
arr = [67, 3, 1, 6, 23, 0, -8, 7, 90]
print(mergesort(arr))
|
import random
from turtle import Turtle, Screen
is_race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make Your Bet", prompt="Which turtle will win the race? Enter a color: ")
print(f"Your bet is on: {user_bet} turtle")
colors = ["red", "orange", "yellow", "green", "blue", "violet"]
y_positions = [-150, -90, -30, 30, 90, 150]
all_turtles = [] # to store multiple turtle instances. Each instances having different states.
# Or we can create many objects having same name using for loop as follows.
# here 6 objects named timmy will be created.
for turtle_index in range(0, 6):
new_turtle = Turtle(shape="turtle") # each turtle object is a 40x40 object.
new_turtle.color(colors[turtle_index])
new_turtle.penup()
new_turtle.goto(x=-235, y=y_positions[turtle_index])
all_turtles.append(new_turtle)
# to prevent the racing to start before the user bet.
if user_bet: # if user_bet has some values this condition will be true
is_race_on = True
while is_race_on:
for turtle in all_turtles:
if turtle.xcor() > 230: # 230 because half of the turtle's body should cross the winning line
is_race_on = False
winning_color = turtle.pencolor()
if winning_color == user_bet:
print(f"You've won! The {winning_color} turtle is the winner!")
else:
print(f"You've lost! The {winning_color} turtle is the winner!")
break
random_distance = random.randint(0, 10)
turtle.forward(random_distance)
screen.exitonclick()
|
''' Rain API Lab '''
import random
from numpy import ma
import requests
from datetime import datetime
from data_rain import RainData
import re
response = requests.get('https://or.water.usgs.gov/non-usgs/bes/hayden_island.rain')
text = response.text
data = re.findall(r'(\d+-\w+-\d+)\s+(\d+)', text)
days_of_rain = []
total_tips = 0
for day in data:
total_tips += int(day[1])
date = datetime.strptime(day[0], '%d-%b-%Y')
days_of_rain.append(RainData(date, int(day[1])))
most_rain = days_of_rain[0]
for day in days_of_rain:
if day.tips > most_rain.tips:
most_rain = day
variance = ma.var([day.tips for day in days_of_rain])
mean = total_tips / len(days_of_rain)
print(f"Start: {days_of_rain[0].date} End: {days_of_rain[-1].date} Variance: {variance} Mean: {mean} Day with most rain: {most_rain.date} with {most_rain.inches} inches")
|
''' Word Count Lab '''
import string
import requests
response = requests.get('http://www.gutenberg.org/files/64217/64217-0.txt')
response.encoding = 'utf-8'
text = response.text
text = text.lower()
for char in string.punctuation:
text = text.replace(char, '')
text = text.split()
words = {}
for word in text:
if word not in words:
words[word] = 1
else:
words[word] += 1
words = list(words.items()) # .items() returns a list of tuples
words.sort(key=lambda tup: tup[1], reverse=True) # sort largest to smallest, based on count
for i in range(min(10, len(words))): # print the top 10 words, or all of them, whichever is smaller
print(words[i])
|
# Assignment 1
import random
import os
import sys
import datetime # for current year
name = input("What is your name? ")
#print("Your name is", name, end="") # end="" -> no new line
#sys.stdout.write(".\n") # sys.stdout.write to have period right after previous string(no whitespace)
age = int(input("What is your age? "))
now = datetime.datetime.now() # current date
year_when_hundo = now.year - age + 100
message = ("The year will be " + str(year_when_hundo) + " when you are 100 years-old.")
print(message)
num = int(input("Enter another number. ")) # prints previous message x times depending on input given by user
print(message * num)
for x in range(num): # prints previous message x times (on separate lines) depending on input given by user
print(message)
|
def pypart(n):
# number of spaces
k = 2 * n - 2
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number spaces
# values changing acc. to requirement
for j in range(0, k):
print(end=" ")
# decrementing k after each loop
k = k - 1
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i + 1):
# printing stars if you want number in place of star(*) then replace print(i," " , end="")
print("* ", end="")
# ending line after each row
print("\r")
def printNumber(n):
k= 2*n -2 #k is number is spaces
for i in range(0,n): # outer loop to handle of number of row
for j in range(0,k): # this looop to handle number of spaces & this will change according to requirment
print(end = " ")
k = k-1 # decrement k after each loop
for j in range(0,i + 1):
print(j ," ",end="")
print("\r") # for end each row
def pascal(n):
k = 2 * n -2
for line in range(1, n+1):
for j in range(0,k):
print(end = " ")
k=k-1
# Every line has number of
# integers equal to line
# number
C = 1; # used to represent C(line, i)
for i in range(1, line + 1):
# print(binomialCoeff(line, i),
# " ", end="")
print(C, end=" ");
C = int(C * (line - i) / i);
print("\r")
# See https://www.geeksforgeeks.org/space-and-time-efficient-binomial-coefficient/
# for details of this function
def binomialCoeff(n, k):
res = 1
if (k > n - k):
k = n - k
for i in range(0, k):
res = res * (n - i)
res = res // (i + 1)
return res
n = int(input("enter any number"))
pypart(n)
printNumber(n)
pascal(n)
|
numbers = []
from statistics import mean
for i in range (0,4+1):
input_number = int(input("Enter number "))
numbers.append(input_number)
for i in range (0,4+1):
print ("Number: {}".format(numbers[i]))
print("The first number is {}".format(numbers[0]))
print("The last number is {}".format(numbers[-1]))
print("The smallest number is {}".format(min(numbers)))
print("The largest number is {}".format(max(numbers)))
print("The average is {}".format(mean(numbers)))
|
"""
Given an array of integers nums, write a method that returns the "pivot" index of this array.
We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.
Example 1:
Input:
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation:
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.
Example 2:
Input:
nums = [1, 2, 3]
Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.
"""
class Solution:
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left, right = 0, sum(nums)
for i, num in enumerate(nums):
right -= num
if left == right:
return i
left += num
return -1
def main():
nums = [1, 7, 3, 6, 5, 6]
result = 3
print(Solution().pivotIndex(nums))
nums = [1, 2, 3]
result = -1
print(Solution().pivotIndex(nums))
if __name__ == '__main__':
main()
|
"""grades = [33, 55,45,87,88,95,34,76,87,56,45,98,87,89,45,67,45,67,76,73,33,87,12,100,77,89,92]
print(sum(grade > sum(grades)/len(grades) for grade in grades))
# a perfect number is equal to the sum of its divisors
def is_perfect(n):
return n == sum(t for t in range(1, n) if n % t == 0)
for i in range(1, 1000):
if is_perfect(i): print(i)
def collatz(n):
sequence = []
while n != 1:
sequence.append(n)
n = n // 2 if n % 2 == 0 else n * 3 + 1
sequence.append(1)
return sequence
print(collatz(1000))
"""
def nonDivisibleSubset(k, arr):
counts = [0] * k
for num in arr:
counts[num % k] += 1
count = 0
for i in range(k // 2 + 1):
opposite = (k - i) % k
if i == opposite:
count += min(counts[i], 1)
else:
count += max(counts[i], counts[opposite])
return count
print(nonDivisibleSubset(3, [1, 7, 2, 4]))
|
# https://leetcode.com/problems/reverse-words-in-a-string-iii/description/
def reverseWords(s):
return ' '.join(word[::-1] for word in s.split())
def main():
tests = [
("Let's take LeetCode contest", "s'teL ekat edoCteeL tsetnoc")
]
for s, result in tests:
assert result == reverseWords(s)
if __name__ == '__main__':
main()
|
"""
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root: return []
paths = []
def find(root, path=''):
if not root.left and not root.right: paths.append(path + str(root.val))
if root.left: find(root.left, path + str(root.val) + '->')
if root.right: find(root.right, path + str(root.val) + '->')
find(root)
return paths
def main():
root = TreeNode(11)
root.left = TreeNode(22)
root.right = TreeNode(33)
root.left.left = TreeNode(44)
print(Solution().binaryTreePaths(root))
if __name__ == '__main__':
main()
|
'''
Merge two sorted array into one.
'''
def merge(nums1, nums2):
return sorted(nums1 + nums2)
def merge(nums1, nums2):
result = []
i, j = 0, 0
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
result.append(nums1[i])
i += 1
else:
result.append(nums2[j])
j += 1
result.extend(nums1[i:])
result.extend(nums2[j:])
return result
def merge(nums1, nums2):
result = [0] * (len(nums1) + len(nums2))
k = len(result) - 1
i = len(nums1) - 1
j = len(nums2) - 1
while i >= 0 and j >= 0:
if nums1[i] > nums2[j]:
result[k] = nums1[i]
i -= 1
else:
result[k] = nums2[j]
j -= 1
k -= 1
while i >= 0:
result[k] = nums1[i]
i -= 1
k -= 1
while j >= 0:
result[k] = nums2[j]
j -= 1
k -= 1
return result
def main():
tests = [
([1, 3, 4, 6], [2, 5, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9])
]
for nums1, nums2, result in tests:
#assert result == merge(nums1, nums2)
print(merge(nums1, nums2))
if __name__ == '__main__':
main()
|
result = set()
with open('base.lst', encoding='utf8') as file:
for line in file:
if line[0] != ' ':
result.add(line.split()[0])
import itertools
anagrams = set()
word = 'фруктовий'
for i in range(3, len(word) + 1):
for x in itertools.combinations(word, i):
#for x in itertools.combinations_with_replacement(word, i):
x = ''.join(x)
for t in itertools.permutations(x):
t = ''.join(t)
if t in result:
anagrams.add(t)
#print(t)
from pprint import pprint
print(len(result))
pprint(sorted(anagrams))
|
"""
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return 0
from collections import deque
q = deque()
q.append((root, 1))
while q:
current, depth = q.popleft()
if not current.left and not current.right: return depth
if current.left: q.append((current.left, depth + 1))
if current.right: q.append((current.right, depth + 1))
def main():
root = None
root = TreeNode(11)
root.left = TreeNode(22)
root.right = TreeNode(33)
root.left.left = TreeNode(44)
root.right.left = TreeNode(55)
print(Solution().minDepth(root))
if __name__ == '__main__':
main()
|
"""
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 1:
Input: [1,3,5,6], 0
Output: 0
https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem
"""
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
#return self.pos(nums, target, 0, len(nums))
lo, hi = 0, len(nums) - 1
while lo <= hi:
m = (lo + hi) // 2
if nums[m] == target: return m
lo, hi = (lo, m - 1) if nums[m] > target else (m + 1, hi)
return lo
def pos(self, nums, target, left, right):
if left >= right:
return left
else:
middle = left + (right - left) // 2
if nums[middle] == target:
return middle
elif nums[middle] < target:
return self.pos(nums, target, middle + 1, right)
else: # nums[middle] > target
return self.pos(nums, target, left, middle - 1)
def main():
tests = [
([1,3,5,6], 5, 2),
([1,3,5,6], 2, 1),
([1,3,5,6], 0, 0),
([], 1, 0),
([1, 3], 2, 1)
]
for nums, target, position in tests[:]:
print(nums, target, position, Solution().searchInsert(nums, target))
if __name__ == '__main__':
main()
|
# https://leetcode.com/problems/valid-parentheses/description/
def isValid(s):
t = []
open_par = {'(', '[', '{'}
close_par = {')': '(', ']': '[', '}': '{'}
for c in s:
if c in open_par:
t.append(c)
else:
if t and t[-1] == close_par[c]:
t.pop()
else:
return False
return len(t) == 0
def main():
tests = [
('(){}[](())({[]})', True),
('((())', False),
('())', False)
]
for s, result in tests:
assert result == isValid(s), s
if __name__ == '__main__':
main()
|
def read_file(filename):
"""Return a list with file lines"""
result = []
with open(filename) as file:
for line in file:
result.append(line.strip())
return result
def find_pattern_naive(text, pattern):
"""Return a list with positions in text where pattern starts"""
if not text or not pattern:
return []
result = []
for i in range(len(text) - len(pattern) + 1):
for j in range(len(pattern)):
if text[i+j] != pattern[j]:
break
else:
result.append(i)
return result
def main():
tests = [
('', '', []),
('a', 'a', [0]),
('abac', 'ab', [0]),
('abac', 'ba', [1]),
('abac', 'ac', [2]),
('abac', 'a', [0, 2]),
('abac', 'abac', [0]),
('aaa', 'a', [0, 1, 2])
]
for text, pattern, result in tests:
print(text, pattern, result, find_pattern_naive(text, pattern))
ulisses = read_file('Ulysses_by_James_Joyce.txt')
pattern = 'forward'
result = []
for line_number, line in enumerate(ulisses, 1):
find_result = find_pattern_naive(line, pattern)
if find_result:
result.extend([(line_number, position + 1) for position in find_result])
print(result)
if __name__ == '__main__':
main()
|
def mult_pol(a, b):
n = max(len(a), len(b))
result = [0] * (2 * n - 1)
for i in range(n):
for j in range(n):
result[i + j] = result[i + j] + a[i] * b[j]
return result
def main():
n = 3
a = [3, 2, 5]
b = [5, 1, 2]
# c = a * b
c = [15, 13, 33, 9, 10]
print(mult_pol(a, b))
if __name__ == '__main__':
main()
|
# https://leetcode.com/problems/reverse-linked-list/description/
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
new_list = None
t = None
while head:
t = head
head = head.next
t.next = new_list
new_list = t
return new_list
|
49. 字母异位词分组
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dict = {}
for item in strs:
key = tuple(sorted(item))
dict[key] = dict.get(key, []) + [item]
return list(dict.values())
1. 两数之和
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
return [i,j]
return []
144. 二叉树的前序遍历
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
res = []
def helper(root):
if not root:
return
res.append(root.val)
helper(root.left)
helper(root.right)
helper(root)
return res
94. 二叉树的中序遍历
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
def inorder(root):
if not root:
return
inorder(root.left)
# 递归完左子树后,处理节点值
ans.append(root.val)
inorder(root.right)
ans = []
inorder(root)
return ans
429. N叉树的层序遍历
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if not root: return [] # 首先判断root是否有内容,如果没有则输出[]
queue = [root] #设置列表queue,前者存放节点
res = [] #设置res,存放值
while queue:
res.append(node.val for node in queue) #开始循环,通过for循环将queue里面的值分离出来一次性加入res中
queue = [child for node in queue for child in node.children] #queue队列通过两个for循环,前面一个取出queue的节点,后一个将取出的节点再取子节点,然后得到queue
return res #最后循环结束输出res
264. 丑数
class Solution:
def nthUglyNumber(self, n: int) -> int:
dp, a, b, c = [1] * n, 0, 0, 0
for i in range(1, n):
n2, n3, n5 = dp[a] * 2, dp[b] * 3, dp[c] * 5
dp[i] = min(n2, n3, n5)
if dp[i] == n2: a += 1
if dp[i] == n3: b += 1
if dp[i] == n5: c += 1
return dp[-1]
|
from random import *
RANDOM_INT = randint(0,99)
def main():
array_one = [0]*100
array_two = [0]*100
array_one = populate_array(array_one)
array_two = populate_array(array_two)
array_two = modify_array(array_two)
answer = check_difference(array_one, array_two)
print "\r\nFIND THE RANDOM MISSING VALUE"
print "============================="
print " "
print " Array One\t|\tArray Two"
print "----------------|---------------"
for i in range(99):
print str(i) + " : " + str(array_one[i]) + "\t\t|\t" + str(i) + " : " + str(array_two[i])
print "--------------------------------"
print "\nThe random value is: ", RANDOM_INT
print "And the missing value from the modified array is: ", answer, "\r\n"
def populate_array(array = []):
for num in range(100):
array[num] = num
return array
def modify_array(array = []):
array[RANDOM_INT] = 0
return array
def sum_array(array = []):
sum = 0
for num in array:
sum += num
return sum
def check_difference(array_initial = [], array_modified = []):
sum_initial = 0
sum_modified = 0
difference = 0
sum_initial = sum_array(array_initial)
sum_modified = sum_array(array_modified)
difference = sum_initial - sum_modified
return difference
if __name__ == "__main__":
main()
|
import unittest
from typing import List
from enum import Enum
class SearchFor(Enum):
FIRST = 0
LAST = 1
def binarySearch(num: int, numbers: List[int]) -> int:
firstIndex = _binarySearch(num, numbers, 0, len(numbers) - 1, SearchFor.FIRST)
if firstIndex is None:
return []
lastIndex = _binarySearch(num, numbers, 0, len(numbers) - 1, SearchFor.LAST)
return list(range(firstIndex, lastIndex+1))
def _binarySearch(num, numbers, left, right, searchFor):
mid = int(left + (right - left) / 2)
if mid < left or mid > right:
return None
if numbers[mid] == num:
if searchFor is SearchFor.FIRST and numbers[mid - 1] == num:
return _binarySearch(num, numbers, left, mid - 1, searchFor)
elif searchFor is SearchFor.LAST and numbers[mid + 1] == num:
return _binarySearch(num, numbers, mid + 1, right, searchFor)
else:
return mid
elif numbers[mid] < num:
return _binarySearch(num, numbers, mid + 1, right, searchFor)
elif numbers[mid] > num:
return _binarySearch(num, numbers, left, mid - 1, searchFor)
else:
pass
class Tester(unittest.TestCase):
def test_BinarySearchFirst(self):
testList = [1, 2, 2, 2, 3, 4, 5]
indexOf2 = _binarySearch(2, testList, 0, len(testList) - 1, SearchFor.FIRST)
self.assertEqual(1, indexOf2)
def test_BinarySearchLast(self):
indexOf2 = _binarySearch(2, [1, 2, 2, 2, 3, 4, 5], 0, 5, SearchFor.LAST)
self.assertEqual(3, indexOf2)
def testBinarySearch(self):
testList = list(range(1, 100))
indexOf40 = binarySearch(40, testList)
self.assertEqual([39], indexOf40)
def testListOfOccurrences(self):
testList = [1, 4, 4, 7, 7, 7, 7, 9, 10]
result = binarySearch(7, testList)
self.assertEqual([3, 4, 5, 6], result)
def testNumberNotInList(self):
testList = [1, 2, 3]
indexOf10 = binarySearch(10, testList)
self.assertEqual(indexOf10, [])
if __name__ == "__main__":
unittest.main()
|
# coding: utf-8
### Generic data selection function
def get_data_selection(dataframe, selector_dict, selector_type='==', copy=True):
"""Return a dataframe containing data that matches all
the criteria defined by `selector_dict`, which is a
dictionary whose keys are the column name and values
are the match criterion.
Note that a copy of the original dataframe is made
by default so any changes made to new data will not be
reflected in the original data.
Input: Pandas dataframe, dictionary of selector values, selector type,
and copy
selector_type is one of ['==' , '<', '>', '<=', '>=' ] and '=='
is the default
copy is True (default) or False and determines if a copy of the
dataframe is made or not
Output: Pandas dataframe for corresponding match
"""
# Check selector_type
if selector_type not in ['==', '<', '>', '<=', '>=']:
raise SyntaxError("The selector_type must be a string and it must be one of the following: ['==', '<', '>', '<=', '>=']")
# Make a copy of the original data
if copy:
table = dataframe.copy()
else:
table = dataframe
# Select the data for each match criterion
for key in selector_dict.keys():
value = selector_dict[key]
if key in table.index.names:
selector_string = ' '.join(['table.index.get_level_values(key)', selector_type, 'value'])
else:
selector_string = ' '.join(['table[key]', selector_type, 'value'])
table = table.ix[eval(selector_string)]
# Clean up the index numbers if appropriate
if copy and (None in table.index.names) and (len(table.index.names) == 1):
table.reset_index(drop=True, inplace=True)
return table
|
from heroenemy import heroenemy
from errors import MismatchError,CharacterError
i=0
list=[]
while(1):
e1 = input("Enter energies of enemies (Use space to separate energies):")
h1 = input("Enter strengths of heroes \n(Use space to separate energies) \n(Number of entries should be equal to that of enemies):")
list.append(heroenemy(e1, h1))
[e,h] = list[i].split(e1,h1)
try:
print(list[i].game(e, h))
except MismatchError:
print("Inequal number of elements for heroes and enemies")
except CharacterError:
print("Wrong delimeter used/Non-numeric character used")
i=i+1
if input("Another game?y/n:") == 'n':
break
|
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(3,GPIO.OUT)
GPIO.setup(7,GPIO.OUT)
GPIO.setup(11,GPIO.IN)
buzzer=15
GPIO.setup(buzzer,GPIO.OUT)
while True:
i=GPIO.input(11)
if i==0:
print "No bike",i
GPIO.output(3,0)
GPIO.output(7,1)
GPIO.output(buzzer,GPIO.LOW)
time.sleep(0.1)
elif i==1:
print "Bike detected",i
GPIO.output(3,1)
GPIO.output(7,0)
GPIO.output(buzzer,GPIO.HIGH)
time.sleep(0.1)
|
def identity(k):
return k
def cube(k):
return pow(k, 3)
def summation(n, term):
"""Sum the first N terms of a sequence.
>>> summation(5, cube)
225
"""
total, k = 0, 1
while k <= n:
total, k = total + term(k), k + 1
return total
def sum_naturals(n):
"""
>>> sum_naturals(5)
15
"""
return summation(n, identity)
def sum_cubes(n):
"""
>>> sum_cubes(5)
225
"""
return summation(n, cube)
|
def square(x):
return x * x
def identity(x):
return x
triple = lambda x: 3 * x
increment = lambda x: x + 1
add = lambda x, y: x + y
mul = lambda x, y: x * y
def make_repeater(f, n):
"""Return the function that computes the nth application of f.
>>> add_three = make_repeater(increment, 3)
>>> add_three(5)
8
>>> make_repeater(triple, 5)(1) # 3 * 3 * 3 * 3 * 3 * 1
243
>>> make_repeater(square, 2)(5) # square(square(5))
625
>>> make_repeater(square, 4)(5) # square(square(square(square(5))))
152587890625
>>> make_repeater(square, 0)(5)
5
"""
"*** YOUR CODE HERE ***"
if n == 0:
return lambda x: x
return lambda x: f(make_repeater(f, n - 1)(x))
|
#CO1102 Programming Fundamentals COURSEWORK 2 (2018/19)
#Authors: Joey Groves and Sean Raisi
import random
def is_secret_guessed(secret_word, letters_guessed): #Authors: Joey Groves and Sean Raisi
letters_guessed = sorted(letters_guessed) #Sorts letters_guessed in alphabetical order
secret_word = secret_word.lower() #Changes secret_word into lowercase
unique_secret_char = [] #Initialises a list of unique characters from secret word
try: #Try statement will attempt to remove duplicate letters from secret_word
for i in secret_word: #Removes duplicates from secret_word
if i not in unique_secret_char:
unique_secret_char.append(i)
except:
print("An Error in removing duplicate characters has occured")
unique_secret_char = sorted(unique_secret_char) #Sorts unique_char in alphabetical order
if set(letters_guessed) > set(unique_secret_char): #If the set of characters of the secret word
return True #is a subset of letters guessed or is equivalent then True is returned
elif set(letters_guessed) == set(unique_secret_char): #otherwise false is returned
return True
else:
return False
def get_current_guess(secret_word, letters_guessed): #Authors: Sean Raisi and Joey Groves
guess= []
for x in range(len(secret_word)):
guess.append("_") #For every letter in the secret word, an underscore is added to an empty list
for i in range (len(letters_guessed)): #The letter in each position for each index in the range of the length of the list letters_guessed
for j in range(len(secret_word)): #and secret_word and if they are equal then the letter is added to the corresponding position in guess
if letters_guessed[i] == secret_word[j]:
guess[j] = letters_guessed[i]
guess = ''.join(guess) #Joins the substring from list 'guess' so it becomes one uniform string
return guess
def choose_secret_word(): #Author: Sean Raisi and Joey Groves
try: #Try statement to attempt to open file: words.txt
words_txt = open("words.txt", "r")
list_words=[] #list_words list initialised
try: #Try statement to attempt to append every single word from file into 'list_words'
for line in words_txt:
list_words.append(line)
rand_word= random.choice(list_words) #rand_word chooses a random word from 'list_words'
rand_word= ' '.join(rand_word.split()) #Then rand_word removes and empty spaces from the start or at the end of the string
finally:
words_txt.close() #File is closed
except:
print("Error: File cannot be opened!") #Exception is raised if program is unable to open file
return rand_word
def decision(): #Author Joey Groves
print()
try: #Try statement to handle non-integer values inputted by the user
decision_user = int(input("Enter '1' if you would like to start another game, otherwise enter any number to quit: "))
except ValueError: #Exception raised if a non-integer value is inputted
print("A non-integer value has been inputted")
return decision_user
def first_game(secret_word): #Author: Joey Groves
print("-----------------------------------------------------") #Opening Main Menu
print(" Welcome to the Hangman Game ")
print(" By: Joey Groves and Sean Raisi ")
print("-----------------------------------------------------")
print()
print("First Game: Secret Word Is Manually Selected")
print()
secret_word = secret_word.lower() #Casts lowercase function onto selected secret word
length_sw = len(secret_word) #Stores length of secret word for while loop
print("The secret word has", str(length_sw), "characters.")
print()
number_of_guesses = 10 #Stores value of no. of guesses user is allowed
count = 0 #Counter to increment number of guesses left for user
letters_guessed = [] #Initialises a list of letters_guessed
win_Bool = False #Initialises a Boolean value for while condition
lose_Bool = False #Initialises a Boolean value for while condition
win_count = 0 #Initialises a count for the number of wins
lose_count = 0 #Initialises a count for the number of loses
while (count != number_of_guesses) and (win_Bool != True) and (lose_Bool != True): #While Loop will stop running if either: count reaches the number of guesses; the user wins or if the user loses
print("You have " + str((number_of_guesses) - (count)) +" guesses") #Variable storing string with number of guesses, the user has left
try:
usr_guess_char = input("Guess a character in the secret word: ").lower() #Gets users input
assert len(usr_guess_char) == 1
if usr_guess_char not in letters_guessed: #Checks to see if user's guess has been guessed before and appends them to the letters_guessed list
letters_guessed.append(usr_guess_char)
else:
print()
print("You have already guessed '", str(usr_guess_char), "'")
tmp_current_guess = get_current_guess(secret_word, letters_guessed) #Gets the current guess and displays the partially guessed secret word
print("The partially guessed word is:", tmp_current_guess)
print()
if is_secret_guessed(secret_word, letters_guessed) == True: #Checks to see if the secret word has been guessed by the user; User Wins
win_Bool = True
print("It's a win!")
win_count += 1
except AssertionError: #Deals with user string input being greater than length 1
print()
print("ERROR: String entered has a length greater than 1, please enter a character")
print()
count += 1 #Increments counter
if (count == number_of_guesses) and (win_Bool == False): #Checks to see if user has ran out of guesses; User Loses
print("You have ran out of guesses\nIt's a loss!")
print("The word was:", str(secret_word))
lose_count += 1
lose_Bool = True
return win_count
def second_game(): #Author: Joey Groves
print()
print("-----------------------------------------------------") #Opening Main Menu
print(" Welcome to the Hangman Game ")
print(" By: Joey Groves and Sean Raisi ")
print("-----------------------------------------------------")
print()
print("Second Game: Secret Word Is Randomly Selected")
print()
secret_word = choose_secret_word() #Casts lowercase function onto selected secret word
length_sw = len(secret_word) #Stores length of secret word for while loop
print("The secret word has", str(length_sw), "characters.")
print()
number_of_guesses = 18 #Stores value of no. of guesses user is allowed
count = 0 #Counter to increment number of guesses left for user
letters_guessed = [] #Initialised a list of letters_guessed
win_Bool = False #Initialises a Boolean value for while condition
lose_Bool = False #Initialises a Boolean value for while condition
win_count = 0 #Initialises a count for the number of wins
lose_count = 0 #Initialises a count for the number of loses
while (count != number_of_guesses) and (win_Bool != True) and (lose_Bool != True): #While Loop will stop running if either: count reaches the number of guesses; the user wins or if the user loses
print("You have " + str((number_of_guesses) - (count)) +" guesses") #Variable storing string with number of guesses, the user has left
try:
usr_guess_char = input("Guess a character in the secret word: ").lower() #Gets users input
assert len(usr_guess_char) == 1
if usr_guess_char not in letters_guessed: #Checks to see if user's guess has been guessed before and appends them to the letters_guessed list
letters_guessed.append(usr_guess_char)
else:
print()
print("You have already guessed '", str(usr_guess_char), "'")
tmp_current_guess = get_current_guess(secret_word, letters_guessed) #Gets the current guess and displays the partially guessed secret word
print("The partially guessed word is:", tmp_current_guess)
print()
if is_secret_guessed(secret_word, letters_guessed) == True: #Checks to see if the secret word has been guessed by the user; User Wins
win_Bool = True
print("It's a win!")
win_count += 1
except AssertionError: #Deals with user string input being greater than length 1
print()
print("ERROR: String entered has a length greater than 1, please enter a character")
print()
count += 1 #Increments counter
if (count == number_of_guesses) and (win_Bool == False): #Checks to see if user has ran out of guesses; User Loses
print("You have ran out of guesses\nIt's a loss!")
print("The word was:", str(secret_word))
lose_count += 1
lose_Bool = True
return win_count
def game_stats(numberOfGames): #Author: Joey Groves
global lose_count #Global Variable lose_count
game_stats_tup = (); #Game Stats tuple initialised
lose_count = numberOfGames - win_count #Calculates loses by subtracting the number of wins from the number of games
avg_win = win_count/numberOfGames #Calclulates the average win of the user
game_stats_tup += (win_count,) #Adds win count, lose count and average win of user in the tuple
game_stats_tup += (lose_count,)
game_stats_tup += (avg_win,)
print()
print()
print("-----------------------------------------------------") #Game Stats Menu
print(" GAME STATS ")
print("-----------------------------------------------------")
print()
print("Number of Wins:", str(game_stats_tup[0]), "\nNumber of Loses:", str(game_stats_tup[1]), "\nAverage Wins for the Player:", str(game_stats_tup[2]), "\nNumber of Games Played:", str(numberOfGames))
print() #Prints Number of wins, loses and games as well as the average number of wins
print()
print("THANK YOU FOR PLAYING OUR GAME")
def Main(): #Author: Joey Groves
global win_count #Global variable win_count
win_count = first_game("dog") #Runs first_game() function and the return value from the outcome of the game is stored
numberOfGames = 1 #Initialises the number of games
game_cont = True #Boolean value for while loop condition
while game_cont != False:
if decision() == 1: #Gets decision from user by calling the decision() function
game_cont = True
numberOfGames += 1 #Increments number of games by 1 if user decides to play another game
win_count += second_game() #Global Variable 'win_count' is incremented by the outcome of the function 'second_game()'
else:
game_cont = False #Ends game and while loop if user decides to stop playing
game_stats(numberOfGames) #Calls the function game_stats(numberOfGames)
if __name__ == "__main__":
Main()
|
# Using a for loop
list_of_lists = []
for i in range(x+1):
for j in range(y+1):
for k in range(z+1):
permutation = [i,j,k]
#print(sum(permutation))
if sum(permutation) != n:
list_of_lists.append(permutation)
print(list_of_lists)
# Using list comprehensions
list_ = [[i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if sum([i,j,k])!= n]
print(list_)
|
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
if n >= 2 and n <= 10:
marks = student_marks[query_name]
if len(marks) == 3:
for index, value in enumerate(marks):
if value >= 0 and value <= 100:
average = sum(marks)/len(marks)
average_float = f"{average:.2f}"
print(average_float)
|
def find_outlier(integers):
odd = []
even = []
for i in integers:
if i%2 == 0:
even.append(i)
else:
odd.append(i)
if len(odd) == 1 and even > 1:
return odd[0]
elif len(even) == 1 and odd > 1:
return even[0]
|
#!/usr/bin/env python
import re
def between(a, b, v):
try:
n = int(v or '')
except ValueError:
return False
return a <= n <= b
def valid_height(v):
m = re.match(r'^([0-9]+)(cm|in)$', v or '')
if m:
x, units = m.groups()
n = int(x)
return units == 'cm' and 150 <= n <= 193 or units == 'in' and 59 <= n <= 76
def main(inp):
passports = [
dict(field.split(':', 2) for field in fields.split())
for fields in inp.split('\n\n')
]
valid = 0
for p in passports:
if between(1920, 2002, p.get('byr')) and \
between(2010, 2020, p.get('iyr')) and \
between(2020, 2030, p.get('eyr')) and \
valid_height(p.get('hgt')) and \
re.match(r'^#[0-9a-f]{6}$', p.get('hcl', '')) and \
p.get('ecl') in 'amb blu brn gry grn hzl oth'.split() and \
re.match(r'^[0-9]{9}$', p.get('pid', '')):
valid +=1
print(valid)
if __name__ == '__main__':
with open('inputs/04') as f:
main(f.read())
|
#Python program to count the length of elements in the given string without the use of predefined function.
string1=input("enter the string1:")
count=0
for x in string1:
count=count+1
print("the length of the given string is "+str(count))
|
number=int(input("enter the table number:"))
limit=int(input("enter the limit of the table:"))
for i in range (1,limit+1,1):
print(str(number)+ "*"+str(i)+"="+str(number*i))
|
#Python program to get an input string from the user and replace all the empty spaces with _ underscore symbol
input_string=input("enter the input string :")
print("The input string is ",input_string)
for x in input_string:
if (x==" "):
replaced_string=input_string.replace(" ","_")
print("The input string after replacing the empty spaces is ",replaced_string)
|
#count the number of vowles in the given string
string=input("enter the the string:")
count=0
vowels=set("aeiou")
for i in string:
if i in vowels:
count=count+1
print("the count is",count)
|
import string
import random
import clipboard
def newpassword(lenght):
if lenght < 4:
print('Error!', 'Password lenght is too short\nTry again!')
else:
chars = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.sample(chars , lenght))
print(password)
if input('Copy password (y/n): ') == 'y':
clipboard.copy(password)
newpassword(int(input('Lenght: ')))
|
lisst = [1, 4, 6, 9, 3, 5]
print(lisst)
lisst.reverse()
print(lisst)
lisst.sort()
print(lisst)
lisst.append(9)
print(lisst)
lisst.insert(2, 69)
print(lisst)
lisst2 = [10, 21]
print(lisst2)
lisst.extend(lisst2)
print(lisst)
print(lisst.count(9))
lisst.remove(69)
print(lisst)
lisst.pop()
print(lisst)
lisst.pop(2)
print(lisst)
lisst2 = [0] * 50
print(lisst2)
lisst2 = lisst
print(lisst2)
lisst2[0] = 9
print(lisst)
#list comprehension
li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd = [li for li in li if li%2 == 1]
print(odd)
|
#!/usr/bin/python
while True:
name = raw_input("What is your name?")
if name == "done":
break
else:
print "Hello " + name
|
"""
CP1404/CP5632 - Practical
Password checker "skeleton" code to help you get started
"""
def main():
symbol = "*"
password = get_password()
while not is_valid_password(password):
print("Invalid password!")
password = get_password()
print("Your {}-character password is valid: {}".format(len(password),password))
def get_password():
print("Please enter a valid password")
print("Your password must contain:")
print("\t1 or more uppercase characters")
print("\t1 or more lowercase characters")
print("\t1 or more special characters")
print("\t1 or more numbers")
password = input("> ")
return password
def is_valid_password(password):
valid_password = False
count_lower = 0
count_upper = 0
count_digit = 0
count_special = 0
if len(password) <= 0 :
return False
for char in password :
if char.isdigit():
count_digit += 1
if char.islower():
count_lower += 1
if char.isupper():
count_upper += 1
if not char.isalnum():
count_special += 1
if count_upper >= 1 and count_lower >= 1 and count_digit >= 1 and count_special >= 1:
valid_password = True
return valid_password
main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 27 21:11:30 2018
@author: Thomas Bury
"""
from sklearn.feature_extraction.text import CountVectorizer
from nltk.corpus import stopwords
from nltk.stem.snowball import SnowballStemmer
import nltk
nltk.download('stopwords')
vectorizer = CountVectorizer()
string1 = "Tom <3 Steph"
string2 = "It is really cold today"
string3 = "How long long is a piece of string?"
string_list = [string1, string2, string3]
bag_of_words = vectorizer.fit(string_list)
bag_of_words = vectorizer.transform(string_list)
# Count stopwords
sw = stopwords.words("english")
# Stemming
stemmer = SnowballStemmer('english')
|
import matplotlib.pyplot as plt
import math
def draw_graph(x, y):
plt.axvline(x=0, color = 'black') # x, y축 추가
plt.axhline(y=0, color = 'black')
plt.plot(x, y)
plt.grid(color='0.8')
plt.show()
def xrange(start, final, interval): # x값 범위 입력받아 저장
numbers = []
while start < final:
numbers.append(start)
start += interval
return numbers
def graph_log(a, b, c, base, xmin, xmax):
if a >= 0:
if 0 - b >= xmin:
xmin = 0 - b + 0.1
elif a < 0:
if 0 - b <= xmax:
xmax = 0 - b - 0.1
x = xrange(xmin, xmax, 0.01)
y = []
for t in x:
y.append(a * math.log(t + b, base) + c)
draw_graph(x, y)
print("방정식을 'y = alog(x+b)+c'처럼 정리해주세요.")
a = float(input('a를 입력해주세요: '))
while True:
base = float(input('로그의 밑을 입력해주세요: '))
if base <= 0:
print('로그의 밑은 0보다 커야합니다.')
elif base == 1:
print('로그의 밑은 1이 될 수 없습니다.')
else:
break
b = float(input('b를 입력해주세요: '))
c = float(input('c를 입력해주세요: '))
xmin = float(input('정의역의 최소값을 입력하세요 : ')) # x값의 범위를 입력받을 수 있도록 수정
xmax = float(input('정의역의 최대값을 입력하세요 : '))
if xmin > xmax: #x값의 최소값이 x의 최대값보다 클 때, 두 값을 바꿈
xstore = xmax
xmax = xmin
xmin = xstore
print('y = {}log{}(x+{})+{}의 그래프를 출력하겠습니다.'.format(a,base,b,c))
graph_log(a, b, c, base, xmin, xmax)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.