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... |
#!/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):
... |
# 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... |
# 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]
# ... |
# 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 ... |
"""
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, defau... |
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)
... |
#生成器总结
#1.语法上和函数类似:生成器函数和常规函数几乎是一样的。它们都是使用def语句进行定义,差别在于
#生成器使用yield语句返回一个值,而常规函数使用return语句返回一个值
#2.自动实现迭代器协议:对于生成器,python会自动实现迭代器协议,以便应用到迭代背景中(如for循环,sum函数)。
#由于生成器自动实现了迭代器协议,所以,我们可以调用它的next方法,并且,在没有值可以返回的时候,生成器自动产生Stoplteration异常
#3.状态挂起:生成器使用yield语句返回一个值。yield语句挂起该生成器函数的状态,保留足够的信息,以便之后从它离开的地方继续执行
#优点一:生成器的好处是延迟计算... |
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') ##删除元素不存在会报错
... |
########### 灰魔法 ###########
#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 = " ... |
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 的 用法 ... |
# 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... |
# 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,... |
# 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/... |
# 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
... |
# 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(bal... |
# 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,... |
# 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 (r... |
## 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 _ i... |
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("u... |
# 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 len... |
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") ... |
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): ... |
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)
# fr... |
'''迭代器'''
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():
... |
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_di... |
##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... |
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) #(wil... |
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 th... |
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:
... |
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()
... |
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 лет. Найти их средний возраст,
# а также определить, на сколько отличается возраст... |
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 play... |
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 ... |
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)... |
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
... |
__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 currencie... |
""" 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)... |
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"... |
''' 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... |
''' 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:... |
# 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)
... |
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
... |
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... |
"""
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 m... |
"""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... |
# 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 =... |
"""
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... |
'''
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 = 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 itert... |
"""
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.ri... |
"""
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... |
# 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]:
... |
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"""
... |
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]... |
# 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
... |
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[i... |
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"
prin... |
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 = _bin... |
# 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
... |
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):")
... |
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.LO... |
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_nat... |
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)
>>> ... |
#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... |
# 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 comprehension... |
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 l... |
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 1... |
#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 repl... |
#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))
prin... |
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.po... |
#!/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: {}".forma... |
#!/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 = CountVecto... |
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 < f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.