text stringlengths 37 1.41M |
|---|
'''
Longest Substring w/o repeating characters
'''
def lengthOfSubstring(inputString):
lenOfStr = len(inputString)
max_len = 0
res = ""
for i in range(lenOfStr):
for j in range(i,lenOfStr):
if(allUnique(inputString,i,j)):
max_len = max(j-i,max_len)
if ... |
import csv
from operator import itemgetter
#This is based on tweet_filter.py, but adapted to look for tweets about school safety, not
with open('aggregated.csv','r') as f:
reader = csv.DictReader(f)
rows = list(reader)
tweets = []
#Make each Tweet a dictionary in a list of dictionaries
for row in rows:
tweets.ap... |
from game_service import Game_service
import os
# Con esta clase lo que se intenta es recolectar y conectar los datos
# ingresados por el jugador/res
class Menu():
def __init__(self):
self.service = Game_service('saves/sum.json')
def clean(self):
if os.name == 'nt':
os.system('cls... |
from collections import namedtuple
from typing import Iterable, Optional, Tuple
def request_relations(client, bsn) -> Tuple[list, list]:
url = f"ingeschrevenpersonen/{bsn}"
response = client.get(
url,
params={"expand": "kinderen.burgerservicenummer,ouders.burgerservicenummer"},
)["_embedde... |
print("Hello World")
name= input("Enter your name please: ")
print("Hello", name)
name= input("What is the name of your best friend?")
print("Hello", name)
my_variable= "John"
print(my_variable)
my_variable= 42
print(my_variable)
my_variable= True
print(my_variable)
# in this exercise, we have learnt about, ... |
#M ve N tamsayıları arasında 5 ile veya 7 ile tam bölünebilen tamsayıların kaç tane olduğunu hesaplayan bir başka program yazınız.
M = int(input("M:"))
N = int(input("N:"))
sayac = 0
for i in range (M,N+1):
if (i % 5 == 0) or (i % 7 ==0):
sayac = sayac + 1
print(sayac) |
#X^K değerini üs alma operatörü (veya eşdeğerlerini) kullanmadan hesaplayan bir program yazınız. Burada X gerçel, K tamsayı değerlerdir.
x = float(input("x:"))
k = int(input("k:"))
i = int()
a = int()
a = x
for i in range(0,k-1):
x = x * a
print(x)
|
#Ağırlıkları yüzde olarak Y1, Y2, Y3 ve Y4 olan
# sınavlardan sırasıyla N1, N2, N3 ve N4 notlarını alan öğrencinin ağırlıklı not ortalamasını bulan bir program yazınız.
Y1 = float(input("1. sınav ağırlık yüzdesi:"))
Y2 = float(input("2. sınav ağırlık yüzdesi:"))
Y3 = float(input("3. sınav ağırlık yüzdesi:"))
Y4 = flo... |
#Girilen M ve N sayılarının her ikisi de pozitif ise ekrana POZİTİF,
# her ikisi de negatif ise ekrana NEGATİF, aksi halde ekrana HİÇBİRİ yazan bir program yazınız.
M = int(input("M:"))
N = int(input("N:"))
if M < 0 and N < 0:
print("negatif")
elif M > 0 and N > 0:
print("pozitif")
else:
print("hiçbiri... |
# 今天學到不同統計量之間特性,
# 試著分析男生女生身高資料,
# 試著回答下面的問題:
# Q1:試著用今天所教的內容,如何描述這兩組資料的樣態?
# Q2: 請問男生和女生在平均身高上誰比較高?
# Q3:請問第二題的答案和日常生活中觀察的一致嗎? 如果不一致,你覺得原因可能為何?
# 上述問題透過 python 語法進行運算, 並將上述答案填寫在 (google 表單)[https://docs.google.com/forms/d/e/1FAIpQLSdDzwpeJl8YLPwZaW8pBZvtuXY9kIbbZLqxcXyzFaoraV5JEA/viewform ]
# library
import matplotl... |
# library
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
import math
import statistics
# 離散均勻分配( Discrete Uniform Distribution )
# 伯努利分配( Bernoulli Distribution )
# 二項分配(Binomial Distribution)
# 今天我們透過作業中的問題,回想今天的內容吧!
# 丟一個銅板,丟了100次,出現正面 50 次的機率有多大。
'''
你的答案
'''
# 這是 b... |
#!/usr/bin/python
# Lili Peng
# Lab5 - Database Loader
# CS3030 - Scripting
import sqlite3
import csv
import random
import os
from sys import argv
# Make sure there are two arguments being passed in
if len(argv) != 3:
print ("Usage: dbload CSVFILE DATABASEFILE")
exit(1)
# Try openning the csv file
ch = ""
tr... |
#!/bin/python3
from random import choice
from random import randint
players = []
file = open('players.txt', 'r')
players = file.read().splitlines()
print('Players:', players)
teamNames = []
file = open('teamNames.txt', 'r')
teamNames = file.read().splitlines()
print('Team names:', teamNames)
chosenTeamName = randi... |
# 打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方
def FunTest():
for i in range(100,999):
a = int(i / 100)
b = int((i % 100) / 10)
c = int(i % 10)
if a*a*a + b*b*b + c*c*c == i:
print(i)
if __name__ == "__main__":
FunTest() |
# https://www.practicepython.org/exercise/2014/02/26/04-divisors.html
number = int(input('Please enter a number: '))
rangeNum = number + 1
theRange = range(1, rangeNum)
newList = []
for element in theRange:
if (number % element == 0):
newList.append(element)
print("This is the list of all the divisors of",... |
# https://www.practicepython.org/exercise/2014/07/05/18-cows-and-bulls.html
def cowsAndBulls():
import random
print("Welcome to the Cows and Bulls game!")
print("-----------------------------------")
print("Instructions:")
print("A 4-digit has been randomly generated. Try to guess it!")
print(... |
content = open("F://code/filter.txt",'r');
filter = [];
for line in content.readlines():
filter.append(line);
input = input("input your words:");
for i in range(len(filter)):
if input.find(filter[i].strip())>-1:
print("yes");
break;
else:
continue;
|
#GuessMyNumber.py
from random import randint
randAnswer = (randint(1,10))
while True:
try:
guess = int (input ("Guess a number between 1-10: "))
break
except ValueError:
print("Please enter a number value: ")
while (guess != randAnswer):
if (guess == randAnswer):
print ("You guessed correctly!")
elif (g... |
import random
# with文でのファイルオープン
# https://bootcamp-text.readthedocs.io/textbook/5_module.html
with open("members.txt", mode="r") as f:
members = f.read()
# 文字列を分割するsplitメソッド
updated_list = members.split()
# ランダムに複数の要素を選択(重複なし): random.sample()
# https://note.nkmk.me/python-random-choice-sample-choices/
firs... |
#Looping Through a Dictionary
print("""We can loop thorugh all of a dictionary's key-value pairs,
keys, or values.
Looping Through All Key-Value Pairs:
for key, value in dict.items():
do something
Looping Through All Keys:
for key in dict.... |
from sys import argv
script, username = argv
prompt = '... '
print(f"Hi {username}. Let's talk about your cat.")
print("What is your cat's name?")
cat = input(prompt)
print("What is your cat's favorite toy?")
toy = input(prompt)
print("Is your cat actually a dog?")
dog = input('is or is not > ')
print(f"""
... |
# x = input('Whose the prettiest kitty?')
# print(x + " is of course!")
y = int(input("Type how many fluffy cats you've counted."))
print(str(y) + " you say?")
print("Well, I say " + str( y * 10) + "!")
|
def order_sandwich(*toppings):
"""Summarize what comes on a sandwich."""
print(f"You ordered a sandwich, with following toppings:")
for topping in toppings:
print(f"- {topping}")
order_sandwich('veggie burger', 'mayo', 'lettice', 'tomato')
order_sandwich('portabello', 'vegan_chipotle_jack')
order... |
import json
def get_stored_number():
"""Retrieve stored number."""
filename = 'store_number.json'
try:
with open(filename) as f:
num = json.load(f)
except FileNotFoundError:
return None
else:
return num
def get_number():
"""Prompt user for their favorite nu... |
def cities(city, country="the United States"):
print(f"{city.title()} is in {country.title()}.")
cities('Washington, D.C.')
cities('Rome', 'Italy')
cities(country='Iceland', city='Reykjavik')
|
class Restaurant:
"""A simple attempt to model a restaurant."""
def __init__(self, name, cuisine):
self.name = name
self.cuisine = cuisine
def describe_restaurant(self):
"""Describe the restaurant."""
print(f"{self.name} serves {self.cuisine} cuisine.")
la_vegan = Restaur... |
def getMaxMinElementOfMatrix(matrix):
maxMinElements = []
max = matrix[0][0]
min = matrix[0][0]
for i in range(0,len(matrix)):
for j in range(0,len(matrix[i])):
if matrix[i][j] > max:
max = matrix[i][j]
if matrix[i][j] < min:
min = matrix[i][j]
maxMinElements.appen... |
import time
import math
startTime = time.time()
res = 0
lower = 0
n = 1
while lower < 9:
lower = 10**((float(n-1))/float(n))
if lower > 9:
lower = 9
else:
lower = int(lower)
res += 9-lower
n += 1
endTime = time.time()
print "The number of n-digits integers that are the nth power of an integer is "+s... |
import sys, math
res = dict()
def factorial(n):
global res
if n in res:
return res[n]
if n == 0:
return 1
else:
res[n] = factorial(n-1)*n
return res[n]
ans = 0
for i in xrange(3, 50000):
sum = 0
for c in str(i):
sum += factorial(int(c))
if sum == i:
ans += i
print ans
|
# TODO: Decompose into functions
def move_forward(size):
print("* Move Forward "+str(size))
def turn_right(degrees):
print("* Turn Right "+str(degrees)+" degrees")
def move_square():
""" This funtion moves the square of size 10 """
size = 10
print("Moving in a square of size "+str(size))
for... |
#!/usr/bin/python
import fileinput
import sys
for line in fileinput.input():
val = line.strip()
if val == '1' or val == '2' or val == '3':
print '1'
elif val == '4' or val == '5' or val == '6':
print '2'
elif val == '7' or val == '8' or val == '9':
print '3'
elif val == '10' or val == '11' or va... |
import sqlite3
dbconnect = sqlite3.connect("mydatabase2.db");
dbconnect.row_factory = sqlite3.Row;
cursor = dbconnect.cursor();
cursor.execute('SELECT * FROM sensors WHERE zone="kitchen"');
for row in cursor:
print(row['sensorID'],row['type'],row['zone']);
cursor.execute('SELECT * FROM sensors WHERE type="door"');
fo... |
def rotate_list(l):
for x in range(3):
a = l.pop(0)
l.append(a)
return l |
def rangoli(N):
if N == 1:
result = "a"
return result
alphabet = "abcdefghijklmnopqrstuvwxyz"
letters = []
row_list = []
for r in range(1, N+1):
row = "-"*(2*N-2*r)
for c in range(1, r+1):
letters += [alphabet[N-c]]
join_let = "-".join(l... |
# TO-DO: Complete the selection_sort() function below
def selection_sort( arr ):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
for j in range(cur_index, ... |
#Fuerza bruta
from string import ascii_letters, digits
from itertools import product
from time import time
caracteres = ascii_letters +digits
def buscar(con):
#Abrir el archivo con las cadenas generadas
archivo = open("combinaciones.txt", "w")
if 3<= len(con) <= 4:
for i in range(3,5):
... |
#list1
list1=[12,-7,5,64,-14]
for i in list1:
if(i>=0):
print(i)
#list2
list2=[12,14,-95,3]
for i in list2:
if(i>=0):
print(i)
|
#!/usr/bin/env python
# -*- coding: utf-8 -
import tsensor
import time
t1 = tsensor.Tsensor()
t_range = (20, 21, 22, -200, 23, 24, 25, 111, 26, 27)
t_prev = t_range[0]
print 't_prev={}'.format(t_prev)
for t in t_range:
if abs((t-t_prev)/t_prev) > 0.3:
t_curr = t_prev
else:
t_prev = t
... |
"""
--- Day 7: The Sum of Its Parts ---
You find yourself standing on a snow-covered coastline; apparently, you landed a little off course. The region is too hilly to see the North Pole from here, but you do spot some Elves that seem to be trying to unpack something that washed ashore. It's quite cold out, so you decid... |
# -*- coding: utf-8 -*-
# @Time : 2020/6/24 10:18
# @Author : guoyunfei.0603
# @File : __init__.py.py
# s = "'abcd'"
# print(s[0:2]) #'a
# 三、 将字符串中的单词位置反转,“hello xiao mi” 转换为 “mi xiao hello”
# (提示:通过字符串分割,拼接,列表反序等知识点来实现)
s = "hello xiao mi"
s1 = s.split(' ')
t = s1[::-1] # 方式一
# print(t,type(t)) 是一个列表 ... |
"""
============================
Author:柠檬班-木森
Time:2020/6/30 20:09
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
"""
python中常用的三种数值类型:
1、整数:int类型
2、浮点数(小数):float类型
3、布尔值:bool类型
True
False
python中用来区分数据类型的函数:type
"""
# 整数
a = 100999999999
# 浮点数
b = 10.11
# 布尔值
c = True... |
"""
============================
Author:柠檬班-木森
Time:2020/7/4 9:43
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
"""
列表的其他方法
sort:排序
# 升序排序 li.sort()
# 降序排序 li.sort(reverse=True)
reverse:列表反转
copy:复制
"""
# 1、列表排序
# li = [1, 23, 44, 4545, 11, 22, 4, 2, 1, 33, 3... |
"""
============================
Author:柠檬班-木森
Time:2020/7/14 14:46
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
print("-----------------------------扩展第一题------------------------")
"""
二、扩展题(选做)温馨提示:难度系数偏高做不出来没关系
1、题目:企业发放的奖金根据利润提成(提示:用到的知识点:条件判断)
用户输入利润
利润低于或等于10万元时,奖金可提10%;
... |
"""
============================
Author:柠檬班-木森
Time:2020/7/21 21:18
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
"""
异常处理:
try:
有可能会出现错误的代码,放到try下面
except:
当try里面的代码出错了,就会执行except里面的代码(可以在此处,处理异常)
else:
try里面的代码没有出现异常就会执行else
finally:
不管try里面的代码是否出现异常,始终都会执行
# ... |
# -*- coding: utf-8 -*-
# @Time : 2020/7/15 16:10
# @Author : guoyunfei.0603
# @File : home_work.py
# 1:简单题
# 1、函数的形参有哪几种定义形式?
"""
三种:
1. 位置参数
2. 默认参数
3. 不定长参数(*args **kwargs)
"""
# 3、函数的实参有哪几种形式?
'''
两种:
1、位置传参(位置参数):按照参数定义的位置进行传递
2、关键字传参(关键字参数):通过参数名字,指定传递
'''
# 2、利用上课讲的for循环嵌套的知识点,封装一个可以打印任意比列三角形的函数... |
"""
============================
Author:柠檬班-木森
Time:2020/7/16 21:11
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
"""
len():获取数据的长度
sum():求和
max():最大值:
min():最小值:
int、float、bool 、str、list、tuple 、dict 、set,range
bool:获取数据的布尔值
python所有的数据都有布尔值,
非零为True: 数据值等于0,或者数据值为None,或者... |
"""
============================
Author:柠檬班-木森
Time:2020/7/4 11:50
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
"""
一、现在有一个列表 li2=[1,2,3,4,5]
第一步:请通过三行代码将上面的列表,改成这个样子 li2 = [0,1,2,3,66,5,11,22,33],
第二步:对列表进行升序排序 (从小到大)
第三步:将列表复制一份进行降序排序(从大到小)
"""
li2 = [1, 2, 3, 4, 5]... |
# -*- coding: utf-8 -*-
# @Time : 2020/7/7 18:01
# @Author : guoyunfei.0603
# @File : dict_json.py
import json
dic = {"name":"丁香","age":22,"job":"teacher"}
# 字典转成json格式
new_json = json.dumps(dic)
print(new_json,'类型是:',type(new_json)) # 类型是: <class 'str'> json在python中是一个字符串
# json转字典
new_dic = json.loads(new_j... |
# 4. Create a list. Append the names of your colleagues and friends to it. Has the id of the list changed?
# Sort the list. What is the first item on the list? What is the second item on the list?
lis = ['Ram', 'Shyam']
lis.append('Anu')
print('Before sorting')
print(lis)
for ind, name in enumerate(lis):
print(ind... |
# 9. Write a binary search function. It should take a sorted sequence and the item it is looking for.
# It should return the index of the item if found.
# It should return -1 if the item is not found.
lis = [9, 18 , 16, 33, 55, 3, 69, 20]
def binary_search(sorted_list, n):
low = 0
high = len(sorted_list) - 1... |
def alanchen():
print("calling multiply with 3 and 7 plus 10 as arguments")
answer = multiply(3, 7, 9)
print(answer)
def multiply(x, y, z):
assert type(z) == int
assert z < 10
return (x * y) + z
if __name__ == "__main__":
alanchen()
|
#printing different values/keys in dictionaries
student = {
"first_name": "Frank",
"last_name": "Smith",
"grade": 11
}
for key in student.keys():
print(key)
>>>first_name
>>>last_name
>>>grade
print()
for val in student.values():
print(val)
>>>Frank
>>>Smith
>>>11
print()
for key, value in student.i... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', nodes: 'List[TreeNode]') -> 'TreeNode':
nodes = set([node.val for node in nodes])
... |
from typing import List
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
words = {w for w in wordDict}
sl = len(s)
record = {0: 1}
for i in range(sl):
if i not in record:
continue
for j in range(i + 1, ... |
from typing import List
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
if n <= 1:
return [nums]
if n == 2:
return [[nums[0], nums[1]], [nums[1], nums[0]]]
orders = self._order_template(nums[1:])
orders = [[nums[... |
from typing import List
class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
min_pair_max = None
curr_min = nums[0]
for num in nums:
if min_pair_max is not None and num > min_pair_max:
return True
if num > curr_min:
i... |
from typing import List
from copy import deepcopy
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
result = []
stack = ['(']
self._do_generate(result, stack, n - 1, n)
return result
def _do_generate(self, result: List, old_stack: List, left: int, ... |
import heapq
from typing import List
class Solution:
def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int:
# priority = -x + y (highest)
# heapq priority = -(-x + y) = x - y (lowest)
q = []
res = -float('inf')
for x, y in points:
while q and ... |
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
class sudokuObj:
def __init__(self):
self.h = False
self.v = False
self.b = False
def checkHorizontal(i, j, flag):
... |
class Solution:
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
grid = [[int(c) for c in string] for string in grid]
def explore(grid, idx, vis):
x, y = idx
dirx = [1, 0, -1, 0]
diry = [0, 1, 0, -1]
if g... |
import time
class Solution:
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def binaryCompare(arr, key):
smaller, larger = 0, 0
for num in arr:
if num > key:
larger += 1
if num < key:
small... |
#!/bin/python3
import sys
def sockMerchant(n, ar):
# Complete this function
sortedar = sorted(ar)
num = 0
highest = len(sortedar)-1
i = 0
while i < highest:
if sortedar[i] == sortedar[i+1]:
num += 1
i += 1
i += 1
return num
n = int(input().strip())
ar = list(map(int,... |
def cipher(text, shift, encrypt=True):
"""
Describe the funtion
Encrypt and decrypt a string using the function by different shift number.
Parameters
----------
text : string
The string that contains alphabet we would like to encrypt or decrypt.
shift : int
... |
def pred_next(x):
temp = {2 * x}
if x % 2 == 0 and x % 3 == 1:
temp.add((x - 1) / 3)
return temp
def step(curr, prev):
nxt = set()
for i in curr:
nxt = nxt.union(pred_next(i))
nxt = nxt.difference(prev)
return nxt
if __name__ == '__main__':
curr = {1}
prev = {1}
... |
"""
Riddler Nation has two coins: the Dio, worth $538, and the Phantus, worth $19. When visiting on vacation, Riddler
National Bank will gladly convert your dollars into Dios and Phanti. For example, if you were to give a bank teller
$614, they’d return to you one Dio and four Phanti, since 614 = 1 × 538 + 4 × 19. But ... |
"""
Riddler Classic
The Monty Hall problem is a classic case of conditional probability. In the original problem, there are three doors,
two of which have goats behind them, while the third has a prize. You pick one of the doors, and then Monty (who
knows in advance which door has the prize) will always open another do... |
'''
From Josh Streeter, graph theory meets ancient Greece in a puzzle that takes two classic mathematical ideas and mashes
them together:
The famous four-color theorem states, essentially, that you can color in the regions of any map using at most four
colors in such a way that no neighboring regions share a color. A ... |
"""
From Robert Berger comes a question of maximizing magnetic volume:
Robert’s daughter has a set of Magna-Tiles, which, as their name implies, are tiles with magnets on the edges that
can be used to build various polygons and polyhedra. Some of the tiles are identical isosceles triangles with one 30
degree angle and... |
"""
From Ricky Jacobson comes a puzzle of seeing how low you can roll:
You are given a fair, unweighted 10-sided die with sides labeled 0 to 9 and a sheet of paper to record your score.
(If the very notion of a fair 10-sided die bothers you, and you need to know what sort of three-dimensional solid it is,
then forget ... |
class myQuickLoader:
"""
This is a better version that figures out what is a class and then
just collects those.
Looks for __init__ and __module__ attribute, and if found assumes
this is a class
"""
myClassCollection = {}
myInstances = {}
def __init__(self):
"""
... |
# 1.师父类
class Master(object):
def __init__(self):
self.kongfu = '[古法煎饼果子配方]'
def make_cake(self):
print(f'运用{self.kongfu}制作煎饼果子')
# 为了验证多继承,添加School父类
class School(object):
def __init__(self):
self.kongfu = '[黑马煎饼果子配方]'
def make_cake(self):
print(f'运用{self.kongfu}制作煎饼果... |
a=1
b=1
while a<=9:
b=1
while b<=a:
print(f'{b}*{a}={a*b}',end=' ')
b+=1
a+=1
print()
str1='itheima'
for i in str1:
if i == 'e':
print('遇到e不打印')
continue
print(i)
|
import numpy as np #import numpy library
#integers
i=10 #integer
print(type(i)) #print out the data type of 1
a_i=np.zeros(i,dtype=int) #declare an array of ints
print(type(a_i)) #will return ndarray
print(type(a_i[0])) #will return int64
#floats
x=119.0 #floating point number
print(type(x)... |
#!/usr/bin/env python
"""Arguments parser demo"""
import argparse
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("input", type=str, help="intput name")
parser.add_argument("output", type=str, help="output name")
parser.add_argument("--debug", action="store_true",
... |
from tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.hi_there = Button(frame, text="Hola", command=self.say_hi)
self.hi_there.pack(side=LEFT)
def say_hi(self):
print("hola todo el mundo!")
root = Tk()
root.title("Ventana ... |
miesiace = ['styczen', 'luty','marzec', 'kwiecień','maj', 'czerwiec','lipiec', 'sierpień','wrzesień', 'październik','listopad', 'grudzień' ]
def miesiac(n):
print(miesiace[n-1])
miesiac(9)
miesiac(7) |
tablica = [12,6,4,9,10]
print(tablica[0], ":" + tablica[0] *"*")
print(tablica[1], ":" + tablica[1] *"*")
print(tablica[2], ":" + tablica[2] *"*")
print(tablica[3], ":" + tablica[3] *"*")
print(tablica[4], ":" + tablica[4] *"*") |
a = 50
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
fib = list(fib(a))
for x in range(len(fib)):
print(fib[x], end=",") |
x=int(input('Wprowadź pierwszą liczbę: '))
y=int(input('Wprowadź drugą liczbę: '))
if x>y:
print(f'Większa liczba to {x}')
elif x<y:
print(f'Większa liczba to {y}')
else:
print('Liczby są równe') |
# 2048 by Ru Li
# ruxuan.li@uwaterloo.ca
# ruxuan.li@gmail.com
import random
from tkinter import *
# legal places a that numbers can be
legal_coordinates = [[0,0],[0,1],[0,2],[0,3],
[1,0],[1,1],[1,2],[1,3],
[2,0],[2,1],[2,2],[2,3],
[3,0],[3,1],[3,2],[3,3]... |
sugar = float(1.5)
butter = float(1)
flour = float(2.75)
aantal = int(input("Hoeveel koekje wil je hebben?"))
print("je hebt")
print(sugar*aantal, "cups sugar,")
print(butter*aantal, "cups butter en")
print(flour*aantal, "cups flour nodig")
|
import collections
import queue
#Annan Miao
#Reference https://eddmann.com/posts/depth-first-search-and-breadth-first-search-in-python/
#Reference https://www.redblobgames.com/pathfinding/a-star/implementation.html
class MazeAgent(object):
'''
Agent that uses path planning algorithm to figure out path to take... |
import torch
from torch.autograd import Variable
# pytorch中的tensor
# x = torch.Tensor(5, 3)
# print(x, x.shape, x.size())
# x = torch.rand(5, 3)
# print(x, x.shape, x.size())
# x_np = x.numpy()
# print(x_np, type(x_np))
# pytorch中的Variable
# x = Variable(torch.ones(2, 2), requires_grad=True)
# # print(x)
# y = x + 2... |
'''Число 125874 и результат умножения его на 2 — 251748
можно получить друг из друга перестановкой цифр.
Найдите наименьшее положительное натуральное x такое,
что числа 5*x, 6*x можно получить друг из друга перестановкой
цифр.'''
def app6():
i = 0
while True:
i += 1
s = {fig: str(i).count(fig) ... |
import random
i=0
while i < 10 :
random_number= random.randint(1,4)
i =i + 1
guessed_number=int(raw_input("Guess an integer (between 1 and 4): "))
print 'random_number is ', random_number
if guessed_number != random_number:
print 'Your guess was not correct.Please tray again'
|
import threading
import time
"""
print_lock = threading.Lock()
def work(i):
with print_lock:
print "thread " + str(i) + " is working on+"
with print_lock:
print "work" + str(i)+ "is done"
time.sleep(1)
for i in range(10):
thread = threading.Thread(target = work, args=(i,))
thread.daemon = True
... |
def get_col_items(board, col):
items = []
for row in board:
items.append(row[col])
return items
def get_box_items(board, row, col):
boxI = row // 3
boxJ = col // 3
items = []
for i in range(boxI*3, (boxI+1)*3):
items.extend(board[i][boxJ*3:(boxJ+1)*3])
return items
f... |
a=int(input("enter a number:"))
if(a>0):
print(' hello '*a)
else:
print('error')
|
# Døme på bruk av while
import random
meir = "J"
while meir == "J":
print(random.randint(1,1000))
meir = input("Vil du ha eit nytt tal? (J eller N)")
print("Du ville ikkje meir, takk for no") |
"""Нейронная сеть с одним входом и несколькими выходами"""
############################################################
weights = [0.3, 0.2, 0.9] # Веса
wlrec = [0.65, 0.8, 0.8, 0.9] # Статистика, из которой берётся точка данных для входа
input = wlrec[0] # Точка данных на вход
def ele_mul(number, vector):
o... |
import json # import json library
import requests # import requests library
url = 'https://api.dictionaryapi.dev/api/v2/entries/en/qa'
response = requests.get(url)
if(response.status_code ==200):
print("Api returns 200") # 200 status code should be generated
assert response.status_code ==200 , "Api return invalid ... |
import tkinter as tk
# 窗口声明
window = tk.Tk()
window.title('my window')
# 窗口p尺寸
window.geometry('200x200')
# 窗口内容-控件
# 定义触发按钮的函数
def insert_point():
var = e.get()
t.insert('insert',var)
def insert_end():
var = e.get()
t.insert('end',var)
# 按钮
b1 = tk.Button(window, text='insert point',
w... |
from collections import defaultdict
class Answers:
def __init__(self):
self.counts = defaultdict(int)
self.respondents = 0
def add(self, yes_answers):
self.respondents += 1
for ans in yes_answers:
self.counts[ans] += 1
def affirmative(self):
return sel... |
import math
def parse_input():
with open('input.txt') as infile:
lines = infile.readlines()
return [int(line) for line in lines]
def find_sum(expenses, target_sum):
for i, expense in enumerate(expenses[:-1]):
matching = target_sum - expense
if matching in expenses[i+1:]:
... |
def get_input(file_path):
with open(file_path) as infile:
lines = infile.readlines()
return [int(line) for line in lines]
def has_sum(search_list, target_sum):
for i, first_num in enumerate(search_list[:-1]):
if first_num >= target_sum:
continue
remaining = target_sum -... |
"""
Program to split Amino Acid sequence and Secondary Structure
"""
import argparse
import sys
import re
def main():
"""
Main Function
:return: Prints the number of protein sequence and secondary structure
"""
args = get_cli_args()
file_2_open = args.INFILE
fh_in = get_fh(file_2_open, "r... |
SUBLIST = 0
SUPERLIST = 1
EQUAL = 2
UNEQUAL = 3
def sublist(list_one, list_two):
if list_one == list_two:
return EQUAL
elif is_sublist(list_one, list_two):
return SUBLIST
elif is_sublist(list_two, list_one):
return SUPERLIST
else:
return UNEQUAL
def is_sublist(list_on... |
animals = ["fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"]
phrases = [
"It wriggled and jiggled and tickled inside her.",
"How absurd to swallow a bird!",
"Imagine that, to swallow a cat!",
"What a hog, to swallow a dog!",
"Just opened her throat and swallowed a goat!",
"I don't k... |
def encode(plain_text, a, b):
if modular_multiplicative_inverse(a, 26) is None:
raise ValueError(r".+")
chars = [c for c in plain_text.lower() if c.isalnum()]
for i in range(len(chars)):
if chars[i].islower():
chars[i] = chr((a * (ord(chars[i]) - 97) + b) % 26 + 97)
for i ... |
NODE, EDGE, ATTR = range(3)
class Node:
def __init__(self, name, attrs):
self.name = name
self.attrs = attrs
def __eq__(self, other):
return self.name == other.name and self.attrs == other.attrs
class Edge:
def __init__(self, src, dst, attrs):
self.src = src
self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.