text stringlengths 37 1.41M |
|---|
def tower(programs):
supported = []
for i in programs:
program = i.split()
if len(program) > 2:
supported.extend("".join(program[3:]).split(","))
for i in programs:
if i.split()[0] not in supported:
return i
return None
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
题目:斐波那契数列。
程序分析:斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……。
在数学上,费波那契数列是以递归的方法来定义:
F0 = 0 (n=0)
F1 = 1 (n=1)
Fn = F[n-1]+ F[n-2](n=>2)
"""
def my_fib(n):
list1 = [0, 1]
if n == 0:
return 0
elif n ==1:
r... |
Write a Python program to reverse a string.
Ans::
def reverse(s):
Str = ""
for i in s:
Str = i + Str
return Str
L = "1234abcd"
reverse(L)
O/p::
dcba4321
|
Write a Python class to find the three elements that sum to zero from a set
Input array : [-25, -10, -7, -3, 2, 4, 8, 10]
Output : [[-10, 2, 8], [-7, -3, 10]]
Ans::
class elements:
def Sum(self,I):
j = len(sorted(I))
result = []
for x in range(j):
for y in range (1,j):
... |
class Number():
def __init__(self,i = 5, j = 1):
self.i = i
self.j = j
print("i is ",self.i, "\nj is ",self.j)
def fun(self):
return (f'{self.i} + {self.j}k')
obj = Number()
print(obj.fun())
print(obj.i)
O/P::
i is 5
j is 1
5 + 1k
5
Deleting::
1)
del obj.i
pri... |
8. Print the each character along with that index in a string i/o - "Python" o/p - P-0 y-1 t-2 h-3 o-4 n-5
Ans:
sol1:
I = "Python"
for x in range(len(I)):
a = I[x]
print('{}-{}'.format(a,x))
sol2:
list_enumerate = list(enumerate(I))
for i in list_enumerate:
print(i)
O/P:
P-0
y-... |
Write a Python program to split a list every Nth element. Go to the editor
Sample list: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
Expected Output: [['a', 'd', 'g', 'j', 'm'], ['b', 'e', 'h', 'k', 'n'], ['c', 'f', 'i', 'l']]
Ans::
L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'... |
#Print unique rows in a given boolean matrix using Set with tuples
Ans:
mat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]]
inputs = set(map(tuple, mat))
for i in list(inputs):
print(i)
O/P::
(1, 1, 1, 0, 0)
(0, 1, 0, 0, 1)
(1, 0, 1, 1, 0)
|
1)
class Mathematics:
def addNumbers(x, y):
return x + y
# create addNumbers static method
Mathematics.addNumbers = staticmethod(Mathematics.addNumbers)
print('The sum is:', Mathematics.addNumbers(5, 10))
O/P::
The sum is: 15
2)
class Dates:
def __init__(self, date):
self.date = date
... |
class MyList(object):
data = None
Next = None
def __init__(self,val):
self.val = val
self.head = None
@classmethod
def add(cls,val):
if not cls.data:
head = cls(val)
cls.data = head
cls.Next = head
else:
head = cls(val... |
Count occurrences of an element in a Tuple
Tuple: (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)
Ans::
T = (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)
Input = int(input("Enter the number:"))
count = 0
for i in T:
if Input == i:
count += 1
print(count,'time')
O/P:
Enter the number:4
0 time
|
Python3 program to remove Nth occurrence of the given word
Ans::
def Remove(Str,word,n):
newword = []
count = 0
for x in Str:
if x == word:
count += 1
if (count != n):
newword.append(x)
else:
newword.append(x)
lst = newword
... |
e = list(range(15))
f = list(range(1,13))
g = list(range(1,12))
def splitter(randomseq, blocks=2):
static_length = len(randomseq)
block_size = static_length//blocks
start = 0
stop = block_size
for block in range(blocks):
if stop < static_length:
yield randomseq[start:stop]
... |
import time
# pulls addresses from a file. Assumes one address per line,
# and ignores empty lines or lines starting with a '#'.
class AddressLoader:
def __init__(self, location):
self.file = open(location, "r")
self.last = None
def is_address(self, line):
opline = self.__clean(line)
is_empty = (o... |
#!/usr/bin/env python3
shopping_lists = []
from list_maker import Listmaker, GroceryItem
while True:
i=0
print("\n\nEnter your Choice or enter Q to quit")
print("1* Create a new shopping list")
print("2* Add items to a list")
print("3* Remove items from the app")
print("4* View your current lists\n")
menu_input... |
#!/usr/bin/env python3
first_number = None
second_number = None
operation = None
class Calculator():
def def __init__(self):
<#code#>
def addition(value1, value2):
print("Add some numbers")
sum = value1 + value2
return sum
def subtraction(value1, value2):
print("Subtract some numbers")
difference = ... |
#!/usr/bin/env python3
class Palindrome:
def __init__(self, input):
self.word = input
self.length = len(input)
self.reversed = ""
def reverse_word(self):
for letter in range (0, self.length):
self.reversed += self.word[letter]
is_palindrome = Palindrome(input("Please enter a word: "))
print(f"The w... |
#!/usr/bin/env python3
friends = ["Kevin", "Josh", "James", "Taylor", "Jeremy"]
for person in friends:
print(person) |
#!/usr/bin/env python3
numbers=[23, 17, 19, 33, 44, 90, 2, 45]
for num in reversed(numbers):
print(num) |
import cv2
def bicubic():
# get scale settings from text file ---
# default bicubic scale is 2
try:
settings = open("settings/settings_bicubic.txt", "r")
bicubic_scale = settings.read()
BICUBIC_SCALE = float(bicubic_scale) #stored in variable
except Exception as e:
... |
# !/usr/bin/env python
# -*- coding: iso-8859-1 -*-
def inverse(liste):
res=""
i=len(liste)
while(i>0):
res=res+liste[i-1]
i=i-1
return res
#return liste[::-1]
def palindrome(phrase):
phraseI=inverse(phrase)
if(phrase==phraseI):
return True
else:
return ... |
def sol(n):
words = []
for i in range(0, n):
words.append(str(input()))
for i in range(0, n):
curr_word = words[i]
if (len(curr_word) > 10):
short_word = curr_word[0] + \
str(len(curr_word[1:len(curr_word)-1])) + curr_word[-1]
words[i] = sho... |
lista=[]
suma=0
for x in range (10):
num= int(input("Ingresa un número"))
lista.append(num)
suma=suma+num
media=suma/10
print("La lista de valores ingresados es:")
print(lista)
print("La suma de los valores ingresados es:")
print(suma)
print("La media de lso valores ingresados es:")
print(media)
|
tupla=(432,7865,432,6754,231,8643,234,8,6,654,)
mayor=tupla[0]
for x in range (1,9):
if tupla[x]>mayor:
mayor=tupla[x]
print("El número mayor de la tupla es:")
print(mayor)
for x in range (1,9):
if tupla[x]<menor:
menor=tupla[x]
print("El número menor de la tupla es:")
print(menor)
|
k = []
print("Phần mêm quản lí nhân viên")
while True:
name = input("Enter worker's name, seperated by ',':")
a = input("nhập chức vụ:")
b = input("nhập mức lương")
c = input("nhập thời hạn hợp đồng")
d = {
"Tên nhân viên":(name),
"chức vụ" : (a),
"mức lương" : (b),
... |
a = ["evenger1", "avenger2", "averger3"]
print(a)
a.pop(1)
print(a)
b = ["evenger1","LOL", "avenger2", "averger3"]
print(b)
c = "LOL"
b.remove(c)
print(b)
if c in b:
print("Chưa xóa LOL")
else:
print("Đã xóa LOL")
|
a = ["Sport", "LOL", "DOTA", "BTS"]
for x in a:
print(x)
b = ["Sport", "LOL", "DOTA", "BTS"]
for y in b:
print(y.upper())
c = ["Sport", "LOL", "DOTA", "BTS"]
for i, item in enumerate(c):
print(i, item.upper())
|
from random import choice, shuffle
g = 0
while True:
a = ["fornite", "Lol", "PUBG", "Dota"]
x = choice(a)
y = [i for i in (x)]
shuffle (y)
print(*y)
e = input("sắp xếp thành 1 từ có nghĩa :")
if e == x:
g = g + 1
print("đúng", g)
else:
print("sai", g)
brea... |
b = ["blue", "red", "teal", "green"]
a = input("nhập vào một vị trí hoặc một nội dung:")
if a.isdigit:
while True:
if 0 <= a <= len(b):
b.pop(a)
print(*b)
break
else:
print("Nhập lại đúng vị trí")
else:
b.remove(a)
print(*b) |
while True:
a = input("your name?")
if a.isdigit():
print("Nhap lai")
else:
print(a)
break |
import sqlite3
from sqlite3 import Error
def conectar():
try:
con = sqlite3.connect('db/datos.db')
return con
except Error as error:
print(str(error))
return None
def insert(_sql, lista):
try:
con = conectar()
if con:
ob_cursor = con.cursor()
... |
import time
class Timer:
def __init__(self, prt=True):
self.start_time = time.time()
self.last_time = self.start_time
self.print = prt
def tick(self, msg=''):
res = time.time() - self.last_time
if self.print:
print('%.6f' % res, msg)
self.last_time ... |
def palindrome(x):
rev=x[::-1]
if x==rev:
print("palindrome")
else:
print("Not a palindrome")
palindrome("OYo")
palindrome("dad")
palindrome("work")
palindrome("eye")
palindrome("111") |
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import... |
import numpy as np
class Perceptron:
def __init__(self, N, alpha=0.1):
"""
The constructor of the perceptron
:param N: number of columns in the feature vector
:param alpha: learning rate (common choices - 0.1, 0.01, 0.001)
"""
# Initializing the weight matrix with r... |
# Filename: number_game_app.py
# Versions: Python 3
# A simple python programming app that showcases use of:
# - lists
# - loops
# - functions
# - user input
# - importing libraries
# - exceptions
# Features:
# - receives number guess from user, validating if within 1-100
# - tell user if hit or miss by comparing to se... |
import os
from quiz import Quiz
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
def welcome():
name = input("Please enter your name: ")
clear_screen()
print("Hi {}! Welcome to Timed Math Quiz App Version 2!".format(name))
print("This game will measure how fast and accurate ... |
# -*- coding: utf-8 -*-
pw=input("請輸入密碼:")
if (pw=="1234"):
print("歡迎光臨")
else :
print("密碼錯誤")
|
#1. Fibonacci series using Generators
def generateFibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, (a+b)
f = generateFibonacci()
counter = 0
for x in f:
print(x, " ")
counter +=1
if(counter > 10):
break
#2. Another implementation
def fib(a=0, b=1):
while True:
... |
number=int(input('enter your number'))
if number==1:
print(' jan31 days')
elif number==2:
print('feb 28 days')
elif number==3:
print('march 31 days')
elif number==4:
print('april 30 days')
elif number==5:
print('may 31 days')
elif number==6:
print('june 30 days')
elif number==7:
print('july 31 dayd')
elif number... |
a=int(input('enter the age'))
b=int(input('enter the age'))
c=int(input('enter the age'))
if a>b and a>c:
print('a bda h ')
elif b>a and b>c:
print('b chota hai a se')
elif c>a and c>b:
print("c bada hai")
else:
print("brabr hai") |
class DecisionTreeClassifier:
"""
Manual implementation of a Decision Tree Classifier
for numeric and/or ranked data, using the metric of gini impurity.
See example.py for sample implementation code.
Instantiation Parameters
----------
max_depth: int, default = None
Similar to the skl... |
import random
from words import words
import string
def get_valid_word(words):
word = random.choice(words)
while '-' in words or ' ' in word:
word = random.choice(words)
return word
def hangman():
word = get_valid_word(words)
word_letters = set(word)
alphabet = set(string.ascii_upperc... |
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def add(num1,num2):
return (num1+num2)
>>> add(3,5)
8
>>> add.__doc__
>>> def try(n1):
SyntaxError: invalid syntax
>>> def trytry(n1):
'wendang'
#zhus... |
#move function
def move(x, source, target):
print("move No.%d from %s to %s" % (x, source, target))
def hanoi(x, source, temp, target):
if x == 1:
move(x, source, target)
else:
hanoi(x-1, source, target, temp)
move(x, source, target)
hanoi(x-1, source, temp, target)
if __name__ == '__main__':
x = int(inpu... |
name = input ("enter the string :")
alist = list(name)
alist.reverse()
finalstring = "".join(alist)
print(finalstring)
|
from collections import defaultdict
class TrieNode:
def __init__(self):
self.children = defaultdict()
self.terminating = False
class Trie:
def __init__(self, K):
self.root = TrieNode()
self.K = K
def get_index(self, ch):
return ord(ch) - ord('a')
def insert(s... |
"""A simple bookkeeping module"""
# Written in Python 3
import sqlite3
import os
import datetime
class Book:
"""A book for bookkeeping"""
def __init__(self, database_name):
"""Open an existing book.
Each instance has its own connection to the database. The connection
will be shared a... |
# 6. В одномерном массиве найти сумму элементов, находящихся между минимальным и максимальным элементами.
# Сами минимальный и максимальный элементы в сумму не включать.
from random import randint
max_, max_i = 0, 0
min_, min_i = 100, 0
arr = [randint(max_, min_) for _ in range(10)]
print(arr)
for i in range(len(arr)... |
# 3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
from random import randint
max_, max_i = 0, 0
min_, min_i = 100, 0
arr = [randint(max_, min_) for _ in range(10)]
print(arr)
for i in range(len(arr)):
if arr[i] > max_:
max_ = arr[i]
max_i = i
if arr[i] ... |
# https://programmers.co.kr/learn/courses/30/lessons/17679?language=python3
def gravity(n, m, board):
for y in range(m):
temp = []
for x in range(n):
if board[x][y] != ' ':
temp.append(board[x][y])
board[x][y] = ' '
for x in range(len(temp)):
... |
# https://www.acmicpc.net/problem/1406
# linked list로 풀 수도 있음, 근데 스택 두개로도 풀 수 있음
# 왼쪽 스택, 오른쪽 스택 사이에 커서 있다고 생각하면 됨
# 커서에 따라서 왼쪽, 오른쪽으로 옮기고 마지막 출력은 (왼쪽 스택) + (오른쪽 스택역순)
from sys import*
input = lambda: stdin.readline().strip()
a = input()
left, right = [], []
for i in range(len(a)):
left.append(a[i])
for i in range(... |
#https://www.acmicpc.net/problem/1918
# 후위 표기식2 문제에 괄호가 추가됨
# 피연산자는 출력(or 문자열 추가)
# 연산자는 우선순위에 따라 처리(스택 빌 때까지 or 스택 맨 위에 있는게 더 우선순위가 낮은거 일때까지 꺼냄)
# 괄호 => 짝궁 괄호 나올 때까지
stack = []
string = input()
priority = {'(':2, '*':1, '/':1, '+':0, '-':0}
res = ''
for i in range(len(string)):
#피연산자면 출력
if 'A' <= string[i] <... |
# https://programmers.co.kr/learn/courses/30/lessons/72412
class Node:
def __init__(self):
self.child = {}
class Trie:
def __init__(self):
self.root = Node()
def insert(self, node, pos, info):
if pos == len(info) - 1:
if 'score' not in node.child:
node.chi... |
# 트라이는 문제 풀면서 적용하기
# https://www.acmicpc.net/problem/5052
from sys import*
input = lambda: stdin.readline().strip()
class Node:
def __init__(self):
self.child = {}
self.end = False
class Trie:
def __init__(self):
self.root = Node()
def insert(self, string):
node = self.roo... |
def hanoi(cnt, a, b, c): #from by to
if cnt == 1:
print(a, c)
return
hanoi(cnt-1, a, c, b)
print(a, c)
hanoi(cnt-1, b, a, c)
return
n=int(input())
res = 0
for i in range(n):
res += (1 << i)
print(res)
if n <= 20: hanoi(n, 1, 2, 3)
|
# https://www.acmicpc.net/problem/2309
# 7개 고르는데 100이 되는 수
def solve(pos, cnt, total):
# 데이터 약해서 가지치기 안해도 됨, 대신 2798 블랙잭은 해야함
# if cnt > 7 or total > 100: return
if pos == 9:
if cnt == 7 and total == 100:
picked.sort()
for p in picked:
print(p)
exi... |
# 양방향으로 만들어볼까
# 삽입 기본은 맨 뒤에, 삽입할 곳 파라미터 주어지면 그 원소 찾아서 삽입하는 오버로딩 함수 만들면 될듯
# 삭제는 찾아서 삭제하도록?
# 그럼 head, tail로 처음과 끝 표시해두자
# 근데 원래 이렇게 복잡함? 예외처리 따로 해주지말고 tail None으로 처리하면 편하려나?
class Node:
def __init__(self, data):
self.data = data
self.prev = self.next = None
def __str__(self):
return str... |
# https://www.acmicpc.net/problem/17143
# pypy3 제출
# 큐에 상어 정보 넣고 dic로 체크하면서 상어 정보 채워넣는 식으로 짜면 될듯?
# 잡는건?? 2차원 board 하나 만들어야 할듯
from sys import*
from collections import*
input = stdin.readline
def changeDirection(d):
if d==U: return D
if d==R: return L
if d==L: return R
if d==D: return U
U, R, D, L = (-1... |
t = int(input())
if t <= 10:
print("Arthur")
if 10 < t <= 30:
print("Luiz")
if 30 < t <= 100:
print("Pedro")
if t > 100:
print("Nenhum") |
'''
Daily Algorithm Coding
2021. 03. 30.
Dijkstra Algorithm
'''
import heapq
INF = 999
n, m = map(int, input().split())
distance = [INF]*(n+1)
visited = [False]*(n+1)
start = int(input())
graph = [[] for i in range(n+1)]
for i in range(m):
a, b, c = map(int, input().split())
graph[a].append((b, c))
print("\ni... |
'''
2021. 06. 05.
Daily Algorithm Coding
DFS/BFS Algorithm
'''
from collections import deque
#basis data
graph = [
#인덱스를 노드, 그 인덱스의 요소가 해당 노드의 인접 노드
#인접 리스트 방식으로 그래프를 표현
[],
[2,3,8],
[1,7],
[1,4,5],
[3,5],
[3,4],
[7],
[2,6,8],
[1,7]
]
#DFS : 1 2 7 6 8 3 4 5
#BFS : 1 2 3 8 7 ... |
'''
2021. 04. 26.
Daily Algorithm Coding
topology sort
'''
from collections import deque
node, edge = map(int, input().split())
indegree = [0]*(node+1)
graph = [[] for _ in range(node+1)]
for i in range(edge):
x, y = map(int, input().split())
graph[x].append(y)
indegree[y] += 1
queue = deque()
for i in range(1, ... |
'''
2021. 04. 23.
Daily Algorithm Coding
Binary Search
'''
arr = [2,4,1,5,3]
def bs(start, end, target, arr):
if start > end: return None
mid = (start+end)//2
if arr[mid] == target:
return mid
if arr[mid] < target:
return bs(mid+1, end, target, arr)
if arr[mid] > target:
return bs(start, mid-1, target, a... |
#Breath First Search
#너비 우선 탐색
from collections import deque
def bfs(graph, start, visited):
queue = deque([start])
#deque 메소드의 인수값으로는 iterable을 받기 때문에
#start라는 인수값 변수를 요소로서 []에 담아서 사용
visited[start] = True
#방문 처리
while queue:
#queue가 빌 때까지
v = queue.popleft()
#가장 먼저 들어온... |
N=int(input()) #입력
count=0
n=0 #각 자리의 숫자를 더한 숫자가 담기는 변수 n
N_list=[] #자리마다 수를 분리하여 담는 리스트
while not 0<=N<=99:
#입력 조건을 충족하는지에 대한 검사
print("입력이 잘못되었습니다. 다시 입력해주세요.")
N=int(input())
finish=N #맨 처음 지정된 숫자
#print() #test
while finish!=N or count==0: #새로운 수가 처음 입력한 수와 같아질 때까지 무한 루프
#각 자리수를 분... |
class Restaurant:
def __init__(self, restaurant_type, cuisine_type):
self.restaurant_type = restaurant_type
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(f"This is {self.restaurant_type} restaurant and it serves {self.cuisine_type}")
def open_restaurant(sel... |
friends = ['Amit', 'Ranjan', 'Jack', 'Paula', 'Mukesh']
print(friends[0])
print(friends[1])
print(friends[2])
print(friends[3])
print(friends[4])
print(f"Good Morning, {friends[0]}")
print(f"Good Morning, {friends[1]}")
print(f"Good Morning, {friends[2]}")
print(f"Good Morning, {friends[3]}")
print(f"Good Morning, {fr... |
""" A class that models real world cars """
class Car:
""" A simple attempt to represent a car"""
def __init__(self, name, model, year):
self.name = name
self.model = model
self.year = year
self.odometer_reading = 0
def describe_car(self):
car = f"{self.name} ... |
FavGames = []
def add_game(game):
FavGames.append(game)
def print_fav_games():
for game in FavGames:
print(game)
def read_file():
file = open("AllFavouriteGames", "r")
for game in file:
add_game(game)
file.close()
def save_file():
file = open("AllFavouriteGames", "w")
... |
import re
import urllib2
import oauth2 as oauth
import json
headers = {}
headers["Accept"] = "application/vnd.github.preview"
url = "https://api.github.com/search/users?q=language:java&"
#request = urllib2.Request(url, headers=headers)
#response = urllib2.urlopen(request)
#results = response.read()
# Create our clien... |
#冒泡排序,第一次排序进行n-1次,如果顺序不对,则调换
def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i] > alist[i+1]:
alist[i],alist[i+1] = alist[i+1],alist[i]
return alist
aList=[54,56,85,91,20,3,26,59,22,30,20,20,20]
print(... |
#优化冒泡排序,提前结束运行
def shortBubbleSort(alist):
passnum = len(alist) - 1
exchange = True
while passnum > 0 and exchange:
exchange = False
for i in range(passnum):
if alist[i] > alist[i+1]:
exchange = True
alist[i],alist[i+1] = alist[i+1],alist[i]
... |
import turtle
tina=turtle.Turtle()
tina.shape('turtle')
tina.color('purple')
def triangle():
tina.forward(100)
tina.lt(120)
tina.forward(100)
tina.lt(120)
tina.forward(100)
tina.lt(120)
triangle()
turtle.mainloop()
|
import turtle
tina=turtle.Turtle()
tina.shape("turtle")
colors=["red","orange","yellow","green","blue","purple","black"]
for color in colors:
angle=360/len(colors)
tina.color(color)
tina.circle(40)
tina.circle(20)
tina.rt(angle)
tina.forward(30)
turtle.mainloop()
|
import turtle
def make_circle(turtle,color,size,x,y):
turtle.penup()
turtle.color(color)
turtle.fillcolor(color)
turtle.goto(x,y)
turtle.begin_fill()
turtle.pendown()
turtle.circle(size)
turtle.end_fill()
tina=turtle.Turtle()
tina.shape("turtle")
make_circle(tina,"green",100,50,0)
mak... |
import ps0 #ps0.py file has to be in the same directory as this file
#0
print("\nTesting Program 0.")
print(0 , "is" , ps0.odd_even(0))
print(24 , "is" , ps0.odd_even(24))
print(5 , "is" , ps0.odd_even(5))
#1
print("\nTesting Program 1.")
print("The number of digits in", 43, "is" , ps0.number_digits(43))
print("The nu... |
import numpy as np
import matplotlib.pyplot as plt
def cost(X, y, theta):
m = y.shape[0]
return 1/(2*m) * np.sum((X.dot(theta) - y) ** 2)
def gradient_descent(X, y, theta, alpha, iterations):
m = y.shape[0]
costs = []
for i in range(iterations):
theta = theta - alpha / m * X.T.dot(X.dot(theta) - y)
costs.app... |
#!/usr/bin/env python
# coding=utf-8
"""
约数之和
数字等于它的约数之和
6=1+2+3
"""
def gcd(n):
result = []
for i in range(1,n):
if n % i == 0:
result.append(i)
return result
def sum_gcd(n):
result = gcd(n)
summary = 0
for i in result:
summary += i
if summary == n:
re... |
#!/usr/bin/env python
# coding=utf-8
"""
有number个button, button可以开可以关,每按一次转换一次操作
现在先按 2n 的顺序依次按button
2, 4, 6,... 2n各按一次
3, 6, 9,... 3n各按一次
...
100n 各按一次
最后灯的状态
"""
size = 10
light = [0 for i in range(size)]
def switch_light(item):
if item == 0:
return 1
else:
return 0
def status(light):
... |
import matplotlib.pyplot as plt
#import random
maxRandom=4294967296
def randomLcg(seed):
seed = (1664525 * seed + 1013904223) % maxRandom
return seed
k=3
n=50000
sumList =[0]*(k*6+1)
seed=12345
for i in range(n):
sum=0
for j in range(k):
seed = randomLcg(seed)
die = int ( seed/maxRandom * 6 + 1 )
#p... |
def main():
dict_ingrediants = {'taco':5, 'meat': 4, 'beef':3, 'rice':1}
print(dict_ingrediants['meat'])
max_value = max(dict_ingrediants['meat'], dict_ingrediants['beef'], dict_ingrediants['rice'])
min_value = min(dict_ingrediants['meat'], dict_ingrediants['beef'], dict_ingrediants['rice'])
remaini... |
#1 请找出以下代码的错误,并修改使其正常运行
# age = input('请输入数字: ')
# if age == 10
# print('小明今年%d岁了'%age)
# print('程序结束')
def age():
age = int(input('请输入数字: '))
if age == 10:
print('小明今年%d岁了'%age)
else:
print('程序结束')
age()
#2 请修改以下代码的错误,并修改使其正常运行(代码实现对列表求和)
# list = [1,2,3,4]
# def run(... |
# def bubble_sort(data):
# data_length = len(data)
# for i in range(data_length):
# for j in range(data_length-i-1):
# if data[j] > data[j+1]:
# temp = data[j]
# data[j] = data[j+1]
# data[j+1] = temp
# if __name__ == "__main_... |
# list = [12, 25, 65, 78, 89, 45, 50]
# search = 50
# for i in range(len(list)):
# result = list[i]
# if result == search:
# print("Found in index: ", i)
# print("Not found this list")
# list = [12, 25, 65, 78, 89, 45, 50]
# search = 50
# found = False
# for i in range(len(list)):
#... |
# def sorted_list(item_value):
# item_length = len(item_value)
# for i in range(item_length - 1):
# mid_index = i
# for j in range(i+1, item_length):
# if item_value[j] < item_value[mid_index]:
# mid_index = j
# if mid_index != i:
# res... |
class queue:
def __init__(self) -> None:
self.item = []
def is_empty(self):
if self.item == []:
return "This is empty"
return "This is not empty"
def enqueue(self, add_item):
self.item.append(add_item)
def dequeue(self):
if len(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python 2.7
# py-heap-sort-demo-1.py
class HeapSortDemo1():
def DisplayData(self, data):
print ', '.join([str(i) for i in data])
def Heapify(self, data, i, size):
left_child = 2 * i + 1
right_child = 2 * i + 2
max = i
if l... |
NORTH, S, W, E = (0, -1), (0, 1), (-1, 0), (1, 0) # directions
turn_right = {NORTH: E, E: S, S: W, W: NORTH} # old -> new direction
turn_left = {NORTH: W, E: NORTH, S: E, W: S} # old -> new direction
def spiral(width, height):
if width < 1 or height < 1:
raise ValueError
x, y = width // 2, height /... |
class Graph():
def __init__(self):
self._adjacency_list = {}
def add_node(self, value):
node = Node(value)
self._adjacency_list[node] = []
return node
def add_edge(self, start_node, end_node, weight=0):
if start_node not in self... |
from data_structures_and_algorithms.data_structures.linked_list_insertions.linked_list_insertions import (
LinkedList, Node
)
""" Required Tests """
# Can successfully add a node to the end of the linked list
# Can successfully add multiple nodes to the end of a linked list
# Can successfully insert a node bef... |
from collections import deque
class BinaryTree:
"""Simple BinaryTree with enough functionality for breadth first adding"""
def __init__(self):
self.root = None
def add(self, value):
node = Node(value)
if not self.root:
self.root = node
return
q ... |
# funtional programming
# ---------------------
# use of function for special modulalisation in could be done.
# they are two types of function
# 1.pre defined
# 2.over defined
# function has 3 main components
# 1.definition
# 2.implementation
# 3.function call
# A function is class function the definition+impleme... |
import wikipedia
from tkinter import *
from tkinter.messagebox import showinfo
win = Tk()
win.title("wikipedia")
win.geometry("500x200")
def serach_wiki():
serach = entry.get()
answer = wikipedia.summary(serach)
showinfo("wikipedia Answer",answer)
label = Label(win,text="wikipedia Search: ")
label.grid(row=0,column=... |
from turtle import turtle
t = Turtle()
def spiral(n):
if n < 300:
t.forward(n)
t.right(89)
spiral(n+1)
spiral(30) |
totalPrice = int(input("Input Price:"))
def vatCalculate(totalPrice):
result = (totalPrice+(totalPrice*7/100))
return result
print("Include Vat 7% :", vatCalculate(totalPrice))
|
car = 'Audi'
for c in car:
print(c)
print(len(car))
print('A' in car)
print('d' in car)
print('Au' in car)
print('x' in car)
print('Ad' in car) |
"""
LEGB
L: Local
E: Enclosing function locals
G: Global
B: Built-in
"""
"""
Local scope :
"""
# Global variable x
x = 14;
def my_func():
# Local variable x
x = 23;
return x;
# print(x);
# print(my_func());
# output - 14 23
# my_func();
# print(x);
# output - 14
"""... |
# https://en.wikipedia.org/wiki/War_(card_game)
import random;
class Deck():
suits = "H D S C".split();
values = "A K Q J 10 9 8 7 6 5 4 3 2".split();
highs = ["J","Q","K","A"];
cards = [];
def __init__(self):
self.prepare_deck();
def prepare_deck(self):
for suit in s... |
# Vector addition function
###################################################
# Student should enter code below
def add_vector(a, b):
x = [(a[0] + b[0]), (a[1] + b[1])]
return x
###################################################
# Test
print add_vector([4, 3], [0, 0])
print add_vector([1, 2], [3, 4])
pri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.