text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# cpp3.py
#
def main(args):
a = int(input("Podaj liczbe a: "))
b = 0
for a in range(a+1):
b = a*a
print(b)
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import turtle
def rysuj(bok, kat, przyrost, warunek):
turtle.forward(bok)
turtle.right(kat)
if kat <= warunek:
rysuj(bok, kat, przyrost, warunek-przyrost)
def main(args):
bok = int(input("Podaj bok: "))
kat = int(input("Podaj kat: ")... |
# Practica6.py-P6E4
#Escribe un programa que te pida dos numeros, de manera que el segundo sea
#mayor que el primero. El programa termina escribiendo los dos numeros tal y como
# pide:
#Escribe un numero: 6
#Escribe un numero mayor que 6: 6
#6 no es mayor que 6. Vuelve a introducir un numero: 1
#1 no es mayor que 6. Vu... |
# Practica6.py-P6E6
#Escribe un programa que pida primero dos numeros (maximo y minimo) y que despues
#te pida numeros intermedios. Para terminar de escribir numeros, escribe un numero
#que no este comprendido entre los dos valores iniciales. El programa termina escribiendo la lista de numeros.
#Escribe un numero: 6
... |
"""
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
""... |
import pygame
class Player():
def __init__(self, screen, settings):
self.width = 12
self.height = 60
self.rect = pygame.Rect(0, 0, self.width, self.height)
self.screen = screen
self.screenRect = screen.get_rect()
self.settings = settings
self.movingUp = Fals... |
print("Welcome to Tip Calcultor")
totalbill = float(input("Whats the total bill $"))
tippercent = float(input("What percent tip you want to give 5,10,15 and 20 ?"))
splitbill = float(input("How many people the bill need to be split across?"))
tippercent = (totalbill*tippercent)/100
grandtotalbill = totalbill + tipper... |
def division(n,m):
if(m==0):
return "division por 0"
if(m>n):
return 0
else:
return division(n-m,m)+1
print(division(10,5))
|
#!/usr/bin/python
# coding: utf8
"""
Contains range related data structures
List of data structures:
- VariableRangeValue
"""
class VariableRangeValue(object):
"""
Contains the range [lower_bound, 0, upper_bound]
Initialize the range to [-inf, 0, +inf]
"""
identifier = ""
bit_vector... |
class Dice:
'''
this class emulates a six sided dice with numbers 1 to 6 on each side such that the sum of numbers on two
opposite sides is always 1.
'''
__slots__ = 't', 'd', 'l', 'r', 'f', 'b'
def __init__(self):
self.t = 1
self.d = 6
self.l = 4
self.r = 3
... |
#problem 1
##names = []
##ages = []
##towns = []
##for i in range(5):
## name = input("Enter the name of person ")
## names.append(name)
## age = input("Enter the age of person ")
## ages.append(age)
## hometown = input("Enter the hometwon of person ")
## towns.append(hometown)
##
##
##print(names)
##... |
#颜色映射
import matplotlib.pyplot as plt
x_values = list(range(1, 6))
y_values = [x ** 3 for x in x_values]
plt.scatter(x_values, y_values, c = y_values, cmap = plt.cm.Reds, s = 60)
plt.title('Cube of Value', fontsize = 22)
plt.xlabel('value', fontsize = 12)
plt.ylabel('cube', fontsize = 12)
plt.tick_params(axis = 'bo... |
# prompt = "Do you have girlfriend ?"
# print(prompt)
# active = True
# while active:
# y_n = input("Please input y/Y or n/N:\n")
# if y_n == 'y' or y_n == 'Y':
# print("Congratulation! you isn't single dog\n")
# elif y_n == 'n' or y_n == "N":
# print("It is shame that you are still a single... |
'''
Дано действительное положительное число a и целоe число n.
Вычислите a^n. Решение оформите в виде функции power(a, n).
Стандартной функцией или операцией возведения в степень
пользоваться нельзя.
Входные данные
Вводится действительное положительное число a и целоe число n.
Выходные данные
Выведите ответ на зада... |
'''Дана строка, возможно, содержащая пробелы.
Определите количество слов в этой строке.
Слово — это несколько подряд идущих букв латинского алфавита
(как заглавных, так и строчных).
Решение оформите в виде функции CountWords (S),
возвращающее значение типа int.
При решении этой задачи нельзя пользоваться дополнительны... |
'''
Даны два натуральных числа n и m. Сократите дробь n/m,
то есть выведите два других числа p и q таких, что n/m=p/q и
дробь p/q — несократимая.
Решение оформите в виде функции ReduceFraction(n, m),
получающая значения n и m и возвращающей кортеж из двух чисел.
Входные данные
Вводятся два натуральных числа.
Выходны... |
'''Заданы две клетки шахматной доски.
Если они покрашены в один цвет, то выведите слово YES,
а если в разные цвета – то NO.'''
y1=int(input('введите номер строки: '))
x1=int(input('введите номер столбца: '))
y2=int(input('введите конечный номер строки: '))
x2=int(input('введите конечный номер столбца: '))
print('YES' i... |
"""A dead-simple implementation of a graph data structure in Python."""
class DiGraph:
"""A simple directed graph data structure."""
def __init__(self):
self.adj = dict()
def add_node(self, label):
self.adj[label] = set()
def add_edge(self, u_label, v_label):
for x in {u_lab... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from xml.dom import minidom
def parseXmlFile(fileName):
xmldoc = minidom.parse(fileName)
booklist = xmldoc.getElementsByTagName('book')
for i in booklist:
for attrName, attrValue in i.attributes.items():
print("%s = %s" % (attrName, attrValue))
print i.getElement... |
def divBy2(decNumber):
binary = []
while decNumber > 0:
rem = decNumber % 2
binary.append(rem)
decNumber = decNumber // 2
return binary[::-1]
def toDecNumber(binary):
decNumber = 0
index = 0
while index < len(binary):
print(decNumber)
decNumber = decNumb... |
from random import choice as choose
from random import randint
def displayBoard(board):
"""The Skeleton of the board and displaying of it"""
print('\n'*20)
print('''
| |
{0} | {1} | {2}
_____|_____|_____
| |
{3} | {4}... |
##############################
## 2 # COMMAND LINE PARSING ## -> @CMD <-
##############################
import sys, logging, os, inspect
import DOC
def str2atom(a):
""" Helper function to parse atom strings given on the command line:
resid, resname/resid, chain/resname/resid, resname/resid/atom,
chain/re... |
#!/usr/bin/env python3
# Head ends here
def next_move(posr, posc, board):
if board[posr][posc] == 'd':
output = "CLEAN"
elif posr % 2 == 0:
if posc < 4:
output = "RIGHT"
else:
output = "DOWN"
elif posr % 2 == 1:
if posc > 0:
output = "LEFT... |
#!/usr/bin/env python3
import re
tests = int(input())
excel = re.compile("^([A-z]+)(\d+)$")
rc = re.compile("^R(\d+)C(\d+)$")
for test in range(tests):
coords = input()
if excel.match(coords):
print("Case {0} is excel.".format(test))
elif rc.match(coords):
print("Case {0} is rc.".format(... |
#!/usr/bin/env python3
MAX = 2000000
def applySieve(prime, sieve):
return [x for x in sieve if x % prime != 0]
prime = 3
sum_primes = 5
sieve = list(range(3, MAX + 1, 2))
while prime < MAX:
sieve = applySieve(prime, sieve)
try:
prime = sieve[0]
except IndexError:
break
sum_primes... |
num1 = 10
num2 = 30
num3 = 5
if num1>num2 and num1>num3:
print(num1)
elif num2>num1 and num2>num3:
print(num2)
else:
print(num3)
#=============check vowel or consonant =================
ch = 'a'
if ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u':
print("vowel.")
else:
print("Consonant.") |
num1 = {1,2,3,4,5}
num2 = set([4,5,6])
num2.add(7)
num2.remove(7)
print(7 in num2)
print(num1 | num2)
print(num1 & num2)
print(num1 - num2)
print(num2 - num1) |
num =5
if num%2 == 0:
print("Even number..")
elif num%3==0:
print("divisible by 3")
else:
print("Odd number")
if 7>3:
if 7>8:
print("Hi")
else:
print("Hello")
num1 = 30
num2 = 20
num3 = 40
if num1 > num2:
if num1 > num3:
print(num1)
else:
print(num3)
if n... |
# map function()
def square(x):
return x*x
num = [10,20,30,40]
a = list(map(square,num))
print(a)
# filter()
num = [1,2,3,4,5]
result = list(filter(lambda x:x%2==0,num))
print(result) |
#Introduction to Function
def add(x,y):
sum = x + y
print(sum)
def addition(x,y,z):
sum = x + y + z
print(sum)
add(5,10)
addition(5,10,15)
|
import itertools
from collections import deque
def part2():
stream = []
with open("in.txt") as f:
for line in f:
stream.append(line.strip())
def is_possible(previous_items, item):
# Returns the boolean answer to the query "can the given item occur in the stream after the given... |
import sys
def part2():
program = []
with open("in.txt") as f:
for line in f:
program.append(line.strip())
# Append a custom instruction to the program to signify end of execution has been reached
program.append("end +0")
def run_instruction(program, index, acc):
# Giv... |
from collections import Counter, deque
def play(a, b):
while len(a) > 0 and len(b) > 0:
if a[0] < b[0]:
b.append(b.popleft())
b.append(a.popleft())
else:
a.append(a.popleft())
a.append(b.popleft())
return b if len(b) else a
def score(x):
re... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
####################################
# AES in ECB mode - set 1/ chall 7 #
####################################
from base64 import b64decode
from Crypto.Cipher import AES
key = 'YELLOW SUBMARINE'
with open('file3.txt', 'r') as f:
cipher = b64decode(f.read())
def dec... |
import sys
import board
import operator
class Player:
BOARD_NAME = 'board.txt'
__board = None
playerNumber = None
def __init__(self, playerNumber, remainingTime):
self.__board = board.readBoard(self.BOARD_NAME)
self.playerNumber = playerNumber
def playGreedyAddStrategy(self):
# Moves are (locat... |
# --------------
import pandas as pd
import numpy as np
import math
#Code starts here
class complex_numbers:
'''
The Complex Number Class
Attributes:
real: real part of complex number
imag: imaginary part of complex number
'''
def __init__(self,real,imag):
... |
# The function is_triangle takes three integer parameters, a, b, and c, and
# and prints either 'Yes' or 'No,' depending on whether or not a triangle can
# be formed from lines with the given integer lengths.
def is_triangle(a, b, c):
if a + b < c or b + c < a or a + c < b:
print 'No'
else:
... |
# The funciton right_justify takes a string, s, as a parameter, and prints the
# string with enough leading spaces so that the last letter of the string is in
# column 70 of the output display.
def right_justify(s):
display_width = 70
string_length = len(s)
leading_spaces = (70 - string_length) * ' '
... |
# The function square_root takes an integer, a, as a parameter,
# and returns an estimate of the square root of a.
def square_root(a):
x = a / 2
epsilon = 0.000001
while True:
print x
y = (x + (a / x)) / 2
if abs(y - x) < epsilon:
break
x = y
print square_root(25... |
from swampy.TurtleWorld import *
from math import pi
world = TurtleWorld()
bob = Turtle()
print bob
bob.delay = 0.1
# The function polygon takes a parameter named t, which is a turtle,
# a parameter named length, which is the length of a side, and a
# a parameter n, which is the number of sides. It uses the turtle to... |
# The function histogram takes a string as a parameter, and returns
# a histogram of the characters in the string.
def histogram(s):
d = dict()
for c in s:
d[c] = d.get(c, 0) + 1
return d
# The function has_duplicates takes a list as a parameter, and returns
# True if there is any element tha... |
print("你好,世界")
# 默认情况下python被视为UTF-8编码
if 3 < 10:
print("判断正确")
# for item in [1,3,4,5,6]:
# print(item)
# for i in range(8):
# print(i, end=' ')
# print(range(10)) #这是一个对象,并不是一个列表,可迭代
# try:
# pass
# except ValueError:
# pass
# except OSError:
# pass
# finally:
# pass
def fun(argu... |
s=input()
l=list(s)
a=''
for i in l:
if i.isnumeric():
a+=i
print(a)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import itertools
from functools import reduce
count = itertools.count(1)
for i in range(5):
print(next(count))
cycle = itertools.cycle('ABC')
for i in range(5):
print(next(cycle))
repeat = itertools.repeat('ABC')
for i in range(5):
print(next(repeat))
takewhi... |
x = 1
y = 2
#
# print(x > 1)
# print(y > 1)
#
# # #and,or, not
# print(x > 1 and y > 1)
# print(x > 1 or y > 1)
# print(not x > 1)
# print(not y > 1)
print(True and True)
print(True or True)
print(not True)
print(False and False)
print(True or True)
print(not False)
print(True and False)
print(True or False)
name =... |
def tiger():
print "wow,the fastest animal.\n"
def cat():
print "The cutest animal\n"
def monkey():
print "The smartest animal\n"
def dog():
print"The most loyal animal\n"
def horse():
print "The royal animal\n"
print "#####Welcome to Short GK ! \n"
print "Animals are the dearest creation of god\n... |
def longest(tree):
return _helper(tree)[0]
def _helper(tree):
if tree == []:
return 0, 0
else:
l, i, r = tree
l_result = _helper(l)
r_result = _helper(r)
combined_depths = l_result[1] + r_result[1]
if combined_depths > l_result[0] and combined_depths > r_res... |
file=open("file.txt","a") #file is created
file.write("Welcome To Computer Department\n")
file=open("file.txt","r") #open it to read mode
newFile=open("newFile.txt","a") #new file created
for i in file: #to copy text from one file to another
print("file.txt content")
print(i)
print("newFile.tx... |
from numpy import *
def compute_error_for_given_points(m, b, points):
totalError = 0
for point in points:
totalError += (point[1] - (m * point[0] + b))**2
return totalError / float(size(points))
def step_gradient(current_b, current_m, points, learning_rate):
gradient_m = 0
gradient_b = 0
N = float(len(points)... |
"""
Item module for the McGyver game
It contain the class 'Item'
"""
from random import randrange
import pygame
from .util import load_image
from .game_config import CELL_WIDTH, CELL_HEIGHT
# For now, there is no public methods for 'Item' so we disable warnings for pylint
class Item: # pylint: disable=too-f... |
import sys
def main():
args = sys.argv
if len(args) < 2:
print(f'{args[0]}: file name not given')
return
for i in range(len(args)):
if i == 0:
continue
do_cat(args[i])
def do_cat(filename):
try:
data = open(filename, "r")
for line in data:
print(line, end="")
except:
... |
import math
import random
#github test
def searchHelp(a,v,l,h):
m=math.floor(((h-l)/2))
mPrime=m+l
printSearch(a,v,l,h,m,mPrime)
if l>h:
return False
elif v==a[mPrime]:
return True
elif v<a[mPrime]:
return searchHelp(a,v,l,mPrime-1)
else:
return searchHelp(a,... |
import datetime
class DataNode():
'''
Hold a key, value, and the time of most recent use.
'''
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
self.last_used_time = datetime.datetime.now()
def get(self):
'''
Return the current value and update the... |
list=[45,56,58,95,32,67,59]
total = sum(list)
print("Sum of all numbers in given list:" , total)
|
"""Calculates the average time of when a sensors turned on.
For example, to track your average bed time.
# Example `apps.yaml` config:
```
average_bed_time:
module: average_time
class: AverageTime
to_watch: input_boolean.sleep_mode
result_senor: sensor.average_sleep_time
from: "13:00"
to: "02:00"
```
"""
... |
import unittest
from battleship import *
from ship import *
class BattleShipTestCase(unittest.TestCase):
def test_A_empty_grid(self):
rows = 2
cols = 4
bs = BattleShip(rows, cols)
bs.show_board_no_ships() # expect 2 rows 4 cols
def test_B_coordinate_conversions(self):
rows = 5
cols = 5
bs = BattleShi... |
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--binary", action="store_true",
help="convert to binary")
parser.add_argument("filename", type=str,
help="the filename to convert")
args = parser.parse_args()
filena... |
# clock2.py - Creates clock2.gif, and animated GIF of a clock (minutes only) showing two rounding modes
# Maarten Pennings 2020 feb 29
import math
from PIL import Image, ImageDraw, ImageFont
# Angle factor (degree to radian)
Rad = 2*math.pi/360
# Size of the generated image
img_width= 800
img_height= 500
... |
import maze
import random
# Create maze using Pre-Order DFS maze creation algorithm
def create_dfs(m):
# TODO: Implement create_dfs
cell_stack = []
current_cell = random.randint(0, m.total_cells - 1)
visited_cells = 1
while visited_cells < m.total_cells:
neighbors = m.cell_neighbors(curren... |
unsorted_list = [3, 1, 0, 9, 4]
sorted_list = []
while unsorted_list:
minimum = unsorted_list[0]
for item in unsorted_list:
if item < minimum:
minimum = item
sorted_list.append(minimum)
unsorted_list.remove(minimum)
print(sorted_list)
|
valid_dna = "ACGT"
sequence = input('pane üks järjestus: ').upper()
condition = all(i in valid_dna for i in sequence)
print('kehtiv järjestus') if condition else print ('ei ole kehtiv järjestus')
|
# -*- coding:utf-8 -*-
# 格式化当前时间
import time
def myTime():
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
myTime()
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 8 19:38:58 2020
@author: NTellaku
"""
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 8 14:22:40 2020
@author: NTellaku
"""
import requests
import pandas as pd
import numpy as np
import scipy.stats as stats
import seaborn as sns
import matplotlib.py... |
def absolute(num):
if num < 0:
return num * (-1)
return num
a = 3.0
b = 4.0
c = 1
print(absolute(a * (b / a - c) - c))
|
Shit_words = ['tangina', 'bobo', 'hayop','gago', 'ulol', 'putangina', 'pakyu', 'fuck', ]
sentence = input('Enter your sentence: ')
new = [x for x in sentence.lower().split()]
text = ''
for word in new:
if word in Shit_words:
a = len(word)
text += '*' * a + ' '
else:
text += word + ... |
string=input("Enter string:")
print("Original String:",string)
res=""
for ch in string:
if ch not in "!@#$%^&*()_-=+{}[]<>,./?';:\|":
res+=ch
print("String without punctuations:"+res) |
string=input("Enter String:")
count=0
for ch in string:
if ch.isupper():
count+=1
print("Number of capital letters in "+string+" is "+str(count)) |
st=input("Enter string")
if st==st[::-1]:
print("String is palindrome")
else:
print("String is not palindrome")
|
import time
class TreeNode:
def __init__(self, value):
self.value = value
self.children = []
def add_child(self):
student = []
possible_numbers = []
for m in self.children:
possible_numbers.append(m.value[0])
student_identity = ... |
from math import pi
def func(x,n=5):
c_list = [1]
for i in range(1,n):
term = -c_list[-1]*((x*x)/(2*i*(2*i - 1)))
c_list.append(term)
return sum(c_list)
def table():
print("%-7s %-16d %-16d %-16d %-16d %d" % ("x",5,25,50,100,200))
for x in [2,4,6,8,10]:
print("%-7.3f" % (pi*x), end ='')
for n in [5,25,5... |
from numpy import *
from matplotlib.pyplot import *
def f(t,x):
return (-x*sin(t))+sin(t)
def eulers(t_k,x_k,h):
return x_k+h*f(t_k,x[-1])
def eulers_midpoint(t_k,x_k,h):
x_midpoint_value = x_k+0.5*h*f(t_k,x_k)
return x_k+h*f(t_k+0.5*h,x_midpoint_value)
for n in [1,2,5,10,100]:
#t values
t = linspace(0,2*pi,... |
from numpy import *
from matplotlib.pyplot import *
def f(x):
return sin(x)
def df(x):
return cos(x)
#notice that pi/2 will not give an answer, why?
#notice that our answer is 4 pi, while the closest zero is at pi, why?
#how can we get pi? HINT: better starting point, aka closer to the zero point
x_start = pi/1.... |
"""
Binary heaps are used a special kind of binary trees
they need to fulfill 2 properties
- complete tree --> all lvls except the last lvl need to be filled
- all vals of child node need to be smaller than parent node val for max heap, & larger for min heap
heaps can perform insertion & removal in worst case lg(n) ti... |
from decimal import *
from builtins import *
# Sets decimal to 50 digits of precision
getcontext().prec = 50
def factorial(n): # Function to find the factorial of a number
if n < 1:
return 1
else:
return n * factorial(n - 1) # Calling the same function recursively
def scratch_pi(n): # B... |
class Student:
def __init__(self, name, birthday, courses):
# public attributes
self.full_name = name
self.first_name = name.split(' ')[0]
self.courses = courses
# protected attributes
self._grades = dict([(course, 0.0) for course in courses])
# birthday is n... |
class Student:
def __init__(self, name, birthday, courses):
# public attributes
self.full_name = name
self.first_name = name.split(' ')[0]
self.birthday = birthday
self.courses = courses
# protected attributes
self._grades = dict([(course, 0.0) for course in ... |
"""This Module contains functions that I don't know where to put anywhere else, that are usable in all modules"""
def relative_position(position, dx, dy, xsize, ysize):
''' Returns the position x distance and y distance from the player's square,
in the form [chunk, x, y]
dx and dy are the distance from the playe... |
a=int(input("entrez un nombre"))
if a%2==0:
print("le nombre est pair")
else:
print("le nombre est impaire") |
"""
Was originally this monstrosity below
[l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2]
if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)),
s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0]
"""
import socket
f... |
import sys
sys.path.insert(0, '../linked_list')
from link_list import LinkList
# ********************************
class Stack():
_data = None
def __init__(self):
self._data = LinkList()
def count(self) -> int:
return self._data.count()
def pop(self) -> object:
... |
from random import randrange
print("Integer Divisions")
while(True):
quit_option=input("Please enter q to quit or enter any other input")
if(quit_option=="q"):
break
a=randrange(5)
b=randrange(5)
try:
query=int(input("what is the value of "+str(a)+"/"+str(b)+"="))
if(query=... |
# tuple is a structure where we can store multiple pieces of information
# similar to a list but a little different
coordinates = (4,5) #use () instead of [] to make a tuple. [] makes a list.
#tuples are immutable (cannot be changed or modified)
#if you try to reassign values in tuple, python will throw error
... |
# following tutorial found on YT, using scikit learn
import numpy as np
import matplotlib.pyplot as pt
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
data = pd.read_csv("train.csv").as_matrix()
clf = DecisionTreeClassifier()
xtrain = data[0:21000, 1:] # takes data from rows 0 to 21000, startin... |
fruitsList = ["Mango", "Watermelon", "Strawberries", "Kiwi"]
print(fruitsList[0])
fruitsList[0] = "Coconut"
print(fruitsList[0])
# 0, 1, 2, 3
# 1, 2, 3, 4
# fruitsTuple = ("Mango", "Watermelon", "Strawberries", "Kiwi")
#A tuple can hold a collection of different data types
# myTuple = (24, True, "String", (1, 2, ... |
i = 0
name = "*"
userinput = int(input("How many layers of \"*\" do you want me to print?"))
while i <= userinput:
print(i * name)
i += 1 |
"""
张量 类似numpy
"""
import torch
x = torch.empty(5, 3) # 构建5*3的未初始化矩阵
print(x)
x = torch.rand(5, 3) # 构建5*3的随机[0-1]初始化矩阵
print(x)
x = torch.zeros(5, 3, dtype=torch.long) # 构建5*3全为0的矩阵,数据类型为long
print(x)
x = x.new_ones(5, 3, dtype=torch.double)
print(x)
x = torch.randn_like(x, dtype=torch.float) # 使用矩阵构建一个类似的随机矩阵
pr... |
"""
PyQt的部分组件,比如勾选框,按钮,滑动条,进度条,日历组件
"""
import sys
def checkbox():
"""
"""
from PyQt5.QtWidgets import QWidget, QCheckBox, QApplication
from PyQt5.QtCore import Qt
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(s... |
def pascal_jesse(lookup_line):
append_one = [1]
if lookup_line == 1:
# First line needs special treatment since it is just a value of "1" in a list. It doesn't follow any calculations.
return [1]
else:
pascal_line = []
for iteration in range(2,lookup_line+1):
# i... |
'''How to work with bits and bytes in python'''
test = "aklsjdf;alksjdf;alksdjfa;lk++sdjf"
test = test.encode('UTF-8')
length = len(test)
print(length)
length_in_bytes = length.to_bytes(4, 'big')
print(length_in_bytes)
length_again = int.from_bytes(length_in_bytes, 'big')
print(length_again)
|
##################################################################################
# Name: Benjamin Tate
# Date: 11/24/2016
# Class: CS 344
# Assignment: Program 5
# Description: A simple python program that will create 3 new text files, write 10
# random lowercase letters and a newline to each, print the random ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Napisz funkcję days_in_year zwracającą liczbę dni w roku (365 albo 366).
"""
def days_in_year(year):
if (year % 4 == 0 and year % 100 != 0 ) or year % 400==0:
num=366
else:
num=365
return num
input = 2019
output = 365
print(days_in_yea... |
#!/usr/bin/python3
for s in range(0, 99):
print("{:02d}, ".format(s), end="")
print(99)
|
#!/usr/bin/python3
def divisible_by_2(my_list=[]):
lista = []
for i in my_list:
if i % 2 == 0:
lista.append(True)
else:
lista.append(False)
return lista
|
# -*- coding: utf-8 -*-
"""
Katherine Lamoureux
MET CS 521
9/8/2019
Homework 1.5
Description: Program that displays the result of an equation
"""
# This section assigns tags
numerator = (9.5 * 4.5 - 2.5 * 3)
denominator= (45.5 - 3.5)
# This section computes the equation
result = numerator / denominator
# This sectio... |
def sortList(data):
newList = []
while data:
minimum = data[0] # arbitrary number in list
for x in data:
if x < minimum:
minimum = x
newList.append(minimum)
data.remove(minimum)
return newList
print(sortList([67, 45, 2, 13, 1, ... |
# import needed modules
import tkinter as tk
from tkinter import messagebox
import logic as log
import sys
# creates snake and apple object
s = log.snake()
a = log.apple()
# main app class
class App(tk.Tk):
# creates tkinter window
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kw... |
# Micah Scott 3/21/19
# imports
import random
import winsound
import time
# define some values
list = []
odetobogo = [329, 329, 349, 392, 392, 349, 329, 293, 261, 261, 293, 329, 293, 261, 261]
i = 0
p = 0
# get user input to append to list
print("Type numbers to be sorted:")
while i < 5:
list.app... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 28 13:50:44 2018
@author: jinyanliu
"""
class IntSet(object):
def __init__(self):
self.vals = []
def insert(self,e):
if e not in self.vals:
self.vals.append(e)
def __str__(self):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 11:41:48 2019
@author: jinyanliu
"""
def intToStr(i):
digits='0123456789'
if i == 0:
return '0'
result = ''
while i>0:
x = i%10
result = digits[x] + result
i = i//10
return result
print (intToS... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 13:44:52 2019
@author: jinyanliu
"""
L = [[1, 2, 3], (3, 2, 1, 0), 'abc']
print(sorted(L, key=len, reverse=True))
L = [1, 2, 6, 5]
print(sorted(L))
L = [1, 'b', 2, 6, 5, 'a']
print(sorted(L))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.