text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python3
"""
Name: Andrew Krubsack
Email: askrubsack@madisoncollege.edu
Description: Midterm Jurassic Park script
"""
print("Name: Andrew Krubsack")
password_database = {}
password_database = {"Username":"dnedry","Password":"please"}
command_database = {}
command_database = {"reboot":"OK. I will reboo... |
class Person:
def __init__(self, name, base_attack, base_deff, base_hp):
self.name = name
self.base_deff = base_deff
self.base_attack = base_attack
self.base_hp = base_hp
def __str__(self):
return self.name
def set_things(self, things):
for thing in things:... |
"""
Complexity: O(n log n)
Evey iteration of input values takes O(log n) time as inputs gets half
in size for every function call
Formula:
- create two subarrys of half size of input array
- merge the subarrys
"""
def merge_sort(n):
"""
>>> merge_sort([2, 3, 1, 4, 2, 5, 6])
[1, 2, 2, 3, 4, 5, 6]
"""... |
#!/usr/bin/python
# to syntax check run
# python -m py_compile <filename>
# import socket library to help us scan for ports
import socket
# the import below is python3 and above
from termcolor import colored
# creating a socket object and assigning it to sock,
# and we are going to use the AF_INET which says it is ... |
class PalindromeChecker:
@staticmethod
def check_palindrome(word):
result = False
odd_letter_set = set()
for letter in word:
if letter in odd_letter_set:
odd_letter_set.remove(letter)
else:
odd_letter_set.add(letter)
if le... |
import constants
MAIN_MENU = """
BASKETBALL TEAM STATS TOOL
---- MENU----
Here are your choices:
1) Display Team Stats
2) Quit
Enter an option >"""
def clean_data(source_data):
""" Takes in the PLAYERS constant
Map the contents of the constant (sorted by experience) into a new dictionary list, cleaning the... |
a=int(input("Informe o primeiro número: "))
b=int(input("Informe o segundo número: "))
numero = a+b
if numero > 1:
for i in range (2, numero):
if (numero % i) == 0:
print ("O número",numero,"não é primo.")
break
if (i == (numero - 1)):
print ("O número",numero,"é primo.")... |
from matplotlib import pyplot as plt
import numpy as np
import random
# https://blog.csdn.net/your_answer/article/details/79259063
# 遗传算法
def coordinate_init(size):
# 产生坐标字典
coordinate_dict = {}
coordinate_dict[0] = (-size, 0) # 起点是(-size,0)
up = 1
for i in range(1, size + 1): # 顺序标号随机坐标
... |
#3과5가 출력된다.
#if True :
#if False:
#print("1")
#print("2")
#else:
#print("3")
#else :
#print("4")
#print("5")
#위 코드를 보면, "사실인 상태에서, 거짓이라면 1과 2를 출력하라 아니라면 3을 출력하라" 라고 되어있다.
#그렇다면 거짓이 아닌 사실인 상태이기 때문에 1과 2는 출력되지 않으며, 거짓이 아니기 때문에 3이 출력된다.
#if false의 조건문이 종료된다. if true의 조건문이 유지... |
nums = [1,2,3,4,5]
avg=sum(nums)/len(nums)
print(avg)
# list의 평균값= list의 모든 원소들의 합/ list의 모든 원소의 갯수
#list의 평균값을 avg로 정의함
#list인 nums안에있는 원소들의 합을 구하기 위해 sum 함수를 사용
# 원소의 갯수로 나눠줘야 하기 때문에 원소갯수를 구하는 len 함수를 사용한 뒤 나눠줌
# avg로 정의한 평균값을 출력한다. |
import abc
import random
class Tombola(abc.ABC):
@abc.abstractmethod
def load(self, iterable):
"""Add items from an iterable"""
@abc.abstractmethod
def pick(self):
"""Remove item at random"""
def loaded(self):
return bool(self.inspect())
def inspect(self):
it... |
from collections import abc
my_dict = {}
print('-'*20)
print("instance of abc {}".format(isinstance(my_dict, abc.Mapping)))
print('-'*20)
tt = (1,2,(30,40))
print("tuple is hashable {}".format(hash(tt)))
tf = (1,2,frozenset([30,40]))
print("frozen set is hashable {}".format(hash(tf)))
print('-'*20)
a = dict(one=1,two=... |
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
input_len = len(input_list)
input_freq = [0] * 10
pivot = 1
merge_opt1 = []
merge_opt2 = []
if inpu... |
class Group(object):
def __init__(self, _name):
self.name = _name
self.groups = []
self.users = []
def add_group(self, group):
self.groups.append(group)
def add_user(self, user):
self.users.append(user)
def get_groups(self):
return self.groups
def get_users(self):
return self.users
def get_name... |
friends = ["Peter", "Pete", "Pet", "Hun", "Jade"]
print(friends)
print(friends[1])
friends[1] = "Julie"
print(friends[1:])
lucky_numbers = [4, 3, 2, 7, 13, 23]
#friends.extend(lucky_numbers)
friends.append("Ralph")
friends.insert(1, "Pony")
friends.remove("Pet")
friends.pop()
print(friends)
friends.inde... |
# tuple is a kind of data structure, similar to a list but with a couple or more differences as below;
# tuples are immutable(cannot modify)
coordinates = (4, 5)
print(coordinates[1])
# coordinates[1] = 10 expected output: TypeError: 'tuple' object does not support item assignment
coordinates_list = [(3, 4), (21, 3)... |
"""CSC110 Fall 2020 Final Project, Extraction File
Copyright and Usage Information
===============================
This file is provided solely for the personal and private use of Professors and TA's
teaching CSC110 at the University of Toronto St. George campus. All forms of
distribution of this code, whether as giv... |
class Product(object):
def __init__(self, price, item_name, weight, brand, cost):
self.price = price
self.item_name = item_name
self.weight = weight
self.brand = brand
self.cost = cost
self.status = "for sale"
def sell(self):
self.status = "sold"
... |
class Animal(object):
def __init__(self, name, health):
self.name = name
self.health = health
def walk(self,rep):
self.health -= 1 * rep
return self
def run(self,rep):
self.health -= 5*rep
return self
def displayHealth(self):
print "Health:", self.... |
# Main Class
# Rahul Shrestha
# CMPS 470-Spring 2016
# Dr. John W. Burris
# https://github.com/rahulShrestha89/470-Assignment1
# This program implements the DECISION_TREE_LEARNING algorithm.
# Input Description:
# First line: (N) Number of examples
# Second line: (X) Number of attributes (Not including go... |
import random
class GameController:
"""
2048游戏算法代码
"""
__list_2048 = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
def move_zero(self):
"""
将一行列表的零元素移动到末尾
:return:
"""
for i in rang... |
"""
Turbulence gradient temporal power spectra calculation and plotting
:author: Andrew Reeves
:date: September 2016
"""
import numpy
from matplotlib import pyplot
def calc_slope_temporalps(slope_data):
"""
Calculates the temporal power spectra of the loaded centroid data.
Calculates the Fourier transf... |
from collections import Counter
input = open("input.txt", "r", encoding="utf-8").read()
phrases = [phrase.split() for phrase in input.splitlines()]
# Part 1
def validPhrases(phrases):
valids = []
for phrase in phrases:
if len(phrase) == len(set(phrase)):
valids.append(phrase)
return... |
import re
input = open("input.txt", "r", encoding="utf-8").read()
rows = input.splitlines()
rs = [row.split("->") for row in rows]
leaves = [elem for elem in rs if len(elem) == 1]
nodes = [elem for elem in rs if len(elem) == 2]
name = re.compile("[a-z]+")
non_roots = [name.findall(node[1]) for node in nodes]
non... |
num = int(input("Введите целое: "))
mult = 1
while (num != 0):
mult = mult * (num % 10)
num = num // 10
print("Произведение цифр равно: ", mult) |
from math import*
def funct(p,n,m):
i=15
s=p*(1+(i/100)/(m/12))**(m/(12*n))
print("Стоимость =",s)
p = int(input("сумма вклада ="))
n = int(input("количество лет="))
m = int(input("количество начислений процентов в год ="))
funct(p, n, m)
|
n=int(input("Enter the n: "))
a=[[0 for i in range(n)]for j in range(n)]
for i in range(n):
for j in range(n):
print(a[i][j],end=" ")
print("\r")
'''
lis=[[3, 5, 9], [6, 4, 7], [9, 1, 0]]
print(lis)
print(lis[1][1])
'''
|
#pattern 1 using while
'''
i=1
while(i<=5):
print('*'*i)
i=i+1
'''
#pattern 1 using for
''''
n=int(input("Enter the number: "))
for i in range(1,n+1):
for j in range(i):
print(i,end=" ")
print()
'''
#patern 2 using for
'''
n=int(input("Enter the number: "))
for i in ran... |
#Leap Year
'''
y=int(input("Enter the Year: "))
if y%4==0:
if y%100==0:
if y%400==0:
print("Leap Year")
else:
print("Not a Leap Year")
else:
print("Not a Leap Year")
else:
print("Not a Leap Year")
'''
#prime number
'''
a=[]
sum1=0
for i in ... |
# select only special character in given input
'''
a=input("Enter the statement with special character and numerics: ")
for i in a:
if i.isalpha()==False:
if i.isdigit()==False:
print(i,end="")
'''
# select only alphabet in given input
'''
a=input("Enter the statement with special ch... |
# -*- coding: utf -8 -*-
from math import sin
x =float(input("Lietotāj, lūdzu ievadi argumentu (x): "))
y = sin(x)
print ("sin(%.2f) = %.2f"%(x,y))
k = 0
a = (-1)**0*x**1/(1)
S = a
print ("a0 = %6.2f S0 = %6.2f"%(a,S))
k = k +1
a = a * (-1)*x*x/((2*k)*(2*k + 1))
S= S + a
print ("a%d = %6.2f S%d = %6.2f"%(k,a,k,S))
... |
from sklearn.cluster import KMeans
import numpy as np
import matplotlib.pyplot as plt
def read_data(filename):
'''
Parameters
----------
filename : string
file storing comma separated data
Returns
-------
numpy array of data stored in filename. file rows are converted to rows... |
#file for testing python staff like tokenization and so on...
string = " asdasd asd asd "
string1 = "asdm,asdasdj,asdasd asd asd asd,ssdadasd ad "
string = "".join(string.split())
print (string)
|
def isFactor(number, factor):
return number % factor == 0
def smallestFactorOf(number):
for i in range(2,number):
if(isFactor(number, i)):
return i |
#Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
sum_of_squares = 0
problem_range = range(1, 101)
for i in problem_range:
sum_of_squares += i*i
print(sum_of_squares)
sum_of_range = sum(problem_range)
square_of_sum = sum_of_range... |
def is_leap(year):
leap = False
if( (year % 4 == 0 and year % 100 != 0) or (year % 100 == 0 and year % 400 == 0)):
leap = True
return leap
if __name__ == '__main__':
year = is_leap(1992)
print year
|
#!/usr/bin/python3
def divisible_by_2(my_list=[]):
if my_list:
list = my_list[:]
for i in range(len(list)):
if (my_list[i] % 2 == 0):
list[i] = True
else:
list[i] = False
return list
|
#!/usr/bin/python3
for i in range(0, 100):
dizaine = i // 10
unite = i % 10
if (unite > dizaine):
if (i == 1):
print("{:02d}".format(i), end="")
else:
print(", {:02d}".format(i), end="")
print()
|
#!/usr/bin/python3
""" Python Network Project """
def find_peak(list):
""" finds a peak in a list of unsorted integers """
peaks = []
if list:
m = list[0]
mpos = 0
for i, elem in enumerate(list):
if elem > m:
m = elem
mpos = i
ret... |
from tkinter import *
import math
# x=column
# y=row
def clear():
valueA.delete(0, 'end')
valueB.delete(0, 'end')
valueC.delete(0, 'end')
def calculate():
a=int(valueA.get())
b=int(valueB.get())
c=int(valueC.get())
#x1=((-(b))+ math.sqrt((math.pow(b,2) * (-4) * a * c))) /(2*a)
#x2=((-(... |
'''
功能:用openpyxl读写excel
Created on 2019年1月21日
@author: Vostory
'''
# coding=utf-8
import openpyxl
filename = r'D:\\PracFolder\\Data\\111.xlsx'
wb = openpyxl.load_workbook(filename) # 读文件
sheets = wb.sheetnames # 获取读文件中所有的sheet,通过名字的方式
print('worksheets is %s' % sheets, type(sheets))
ws = wb[sheets[0]] # 获取第一个shee... |
# Напишите программу, которая будет разрезать большую прямоугольную область на N \times NN×N одинаковых прямоугольных областей.
# Области задаются четырьмя координатами: минимальной широтой, минимальной долготой, максимальной широтой, максимальной долготой.
#
# При выводе области должны быть упорядочены по возрастанию ... |
# В качестве ответа введите все строки наибольшей длины из входного файла, не меняя их порядок.
#
# В данной задаче удобно считать список строк входного файла целиком при помощи метода readlines().
#
# Ссылка на входной файл: https://stepik.org/media/attachments/lesson/258920/input.txt
with open('input6.txt') as file:... |
# Ученые нашли табличку с текстом на языке племени Мумба-Юмба.
# Определите, сколько различных слов содержится в этом тексте.
# Словом считается последовательность непробельных символов идущих подряд, слова разделены одним или большим числом пробелов или символами конца строки.
# Большие и маленькие буквы считаются раз... |
# Выведите в обратном порядке содержимое всего файла полностью.
# Для этого считайте файл целиком при помощи метода read().
#
# Ссылка на входной файл: https://stepik.org/media/attachments/lesson/258921/input.txt
data = open('input7.txt', 'r')
u = data.read()
print(u[::-1])
|
from func import delFinish
three = "three "
str_1 = delFinish(three + three + three)
str_2 = delFinish(three * 3)
print(str_1)
print(str_2)
|
#Ex.0025 - Crie um programa que leia um nome e diga se existe 'silva' no mesmo
nome = str(input('Escreva seu nome:'))
print('Existe Silva no nome: {}'.format('SILVA' in nome.upper()))
|
#Faça um programa que leia um número inteiro e mostre na tela o sucessor e seu antecessor.
n = int(input('Digite um valor:'))
print('Analisando o valor de {}, seu antecessor é {} e o seu sucessor é {}'.format(n, (n-1), (n+1)))
|
#Ex.0017 - Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um Triângulo Retângulo calcule e mostre o comprimento da Hipotenusa
#Incluindo importação
from math import hypot
o = float(input('Digite o cateto oposto:'))
a = float(input('Digite o cateto adjacente:'))
h = hypot(a, o)
... |
import itertools
import numpy as np
def minimum_distance_v(v1, v2):
vdiff = v2 - v1
if abs(vdiff) < 0.5:
return vdiff
elif v1 > 0.5:
return 1 - abs(vdiff)
else:
return -1 + abs(vdiff)
def minimum_distance_point(p1, p2):
return [minimum_distance_v(v1, v2) for (v1, v2) in zi... |
#!/usr/bin/python3
'''
Author: Aastha Shrivastava
PRN: 19030142001
Date modified: 27th JULY 2019
7th August 2019: added exception handling
Description: Program reads file supplied by user, takes an intger value n from user and writes the file contents in new file
without every nth character on each line... |
# A simple hangman game written in python
import random
print("Welcome to HangMan")
#List of words
word_list = ["Youva","Jupyter","Speed","Function"]
# Choosing a random word from the list
word = list(random.choice(word_list))
guess_word = ['*']*len(word)
guess_count = len(word)+2
score = 0
# Running game loop till use... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
'''Function to create binary search tree from its preorder of elements
'''
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
... |
'''
Description: Program to display a simple slideshow using Tkinter.
'''
from tkinter import *
import time
images=["DSC_0511","DSC_0512"]
def slide():
#while True:
for i in images:
image = PhotoImage(file=i+".JPG.png")
label = Label(image=image)
#label.place(x=0,y=0)
... |
from .base import Shape
class Circle(Shape):
def __init__(self, radius, **kwargs):
super().__init__(**kwargs)
self.radius = radius
def draw(self, turtle):
turtle.penup()
turtle.goto(self.center_x, self.center_y - self.radius) # From docs: The center is radius units left of t... |
people = [{'name': "Мария", 'gender': "female", }, {'name': "Калоян", 'gender': "male", }, ]
def print_person(person: dict):
print("{} ({}) is interested in {}".format(
person['name'],
person['age'],
', '.join(person['interests'])
))
def print_people(people: list):
for person in ... |
# today we are going to learn about lists and for loops and while loops
# Yesterday, we learned about conditions and comparisons.
# today, we will learn about:
# lists
# string
# in/not in
# loops
# hopefully function!
'''
Lists are pretty cool. It's something you could maybe put a high score in.
you create ... |
# today we are going to learn about lists and for loops and while loops
# Yesterday, we learned about conditions and comparisons.
# today, we will learn about:
# lists
# string
# in/not in
# loops
# hopefully function!
'''
in/not in
in and not in is very useful for string and lists.
You can asks python to c... |
def fib(n):
tail = [0, 1]
for i in range(1, n):
tail.append(sum(tail[-2:]))
return tail[-1]
if __name__ == '__main__':
print(fib(4))
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import sys
class Solution:
max_sum = -sys.maxsize-1
def maxPathSum(self, root: TreeNode) -> int:
self.max_gain(root)
return self.max_... |
# When a person has a disease, they infect exactly R other people but only on the very next day. No
# person is infected more than once. We want to determine when a total of more than P people have
# had the disease.
p = int(input()) # total people to be infected
n = int(input()) # day 0
r = int(input()) # value of r
... |
list1 = [6, 19, 23, 49, 8, 41, 20, 53, 56, 87]
def find_max(itemlist):
if len(itemlist) == 1:
return itemlist[0]
op1 = itemlist[0]
op2 = find_max(itemlist[1:])
if op1 > op2:
return op1
else:
return op2
print(find_max(list1))
|
'''
Question:
Define a class which has at least five methods:
getInteger: to get two integers from console input
printIntegers: to print integers.
addInteger: to add two integers together
subtractInteger: to subtract two integers
powerInteger: to get the power of the first integer to the power of second intger
... |
'''
Question:
Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H:
C is 60. H is 10.
D is the variable whose values should be input to your program in a comma-separated sequence.
Example
Let us assume t... |
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# The following code reads all the Gapminder data into Pandas DataFrames. You'll
# learn about DataFrames next lesson.
path = '/datasets/ud170/gapminder/'
employment = pd.read_csv(path + 'employment_above_15.csv', index_col='Country')
... |
list5 = [1, 2.5, 3, 4.25, 6, 7, 9.5]
res = []
res = list(x for x in list5 if x%2!=0)
# for i in list5:
# if i%2 != 0:
# res.append(i)
print(res) |
while True:
try:
num1 = input("enter number")
if (len(num1) == 4):
print("enter number is four digit only")
break
except ValueError:
print("Enter number with only four digits") |
import math
input_values = input("Enter the values in a comma-separated sequence:")
split_values = input_values.split(',')
C = 50
H = 30
for i in split_values:
D = int(i)
Q = math.sqrt((2 * C * D) / H)
print("For D Value of {} result is {}".format(D, Q)) |
#Answer: Yes we can assign a diffterent data type in Python as its dynamic programming.
a = 25.3
print(a)
a = 'Hello'
print(a) |
lucky_number = 9
counter = 5
while counter > 0:
number = eval(input("Guess the lucky number:"))
if number == lucky_number:
print("Good Guess!")
break
else:
if counter > 1:
print("Try again!")
counter -= 1
if counter == 0:
print("Sorry but that was ... |
"""
This program creates a network out of a formatted text file and finds the path of least resistance
(lowest weight edges). To achieve this it uses Kruskal's minimum spanning tree algorithm together with
a breadth first search algorithm.
NETWORK : contains the nodes or "cities" as well as the edges (roads).
PA... |
"""
greedy_3_tree.py
Module that contains the Greedy 3 Tree heuristics definition.
"""
import network
import sys
import utils
import numpy as np
def Greedy3Tree(topology: network.Network):
mid_points = MinDistance3Connected(topology)
mid_point_pairs = MidPoint6Connected(topology, mid_points)
MidPoint... |
# 字符串
str1 = "hello python"
str2 = 'hello world'
print(str1)
print(str1[2])
print(str2)
print(str2[3])
for char in str2:
print(char)
print(len(str2)) |
"""
1. 两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
https://leetcode-cn.com/problems/two-sum/
"""
class Solution:
def twoSum(self, nums, target: int):
di... |
# 异常
def excption1():
try:
# 不能确定正确执行的代码
num = int(input("请输入一个整数:"))
except:
# 错误的处理代码
print("请输入正确的整数")
print("-" * 50)
def excption2():
"""捕捉错误类型"""
try:
# 提示用户输入一个整数
num = int(input("输入一个整数:"))
# 使用 8 除以用户输入的整数并且输出
result = 8 / ... |
"""
给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。
假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
注意:每次拼写时,chars 中的每个字母都只能用一次。
返回词汇表 words 中你掌握的所有单词的 长度之和。
示例 1:
输入:words = ["cat","bt","hat","tree"], chars = "atach"
输出:6
解释:
可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。
示例 2:
输入:words = ["hello","world",... |
import string
file_name = input('Enter the file name (ex. palindromes.txt)> ')
unwanted = string.punctuation + ' '
def is_palindrome(str):
# Remove the unwanted chars
new_str = filter(lambda x: x not in unwanted, str.lower())
if new_str == new_str[::-1]:
return True
with open(file_name, 'r') as f:
for li... |
#Write your code below this line 👇
#Hint: Remember to import the random module first. 🎲
import random
print("Welcome. This is a coin toss programme.")
coin_side_chosen = int(input("Type 0 for Heads and 1 for Tails."))
if coin_side_chosen == 0:
print("You chose Heads.")
else:
print("You chose Tails.")
comp_coi... |
import pygame
# Add your favorite background color
background_colour = (0, 0, 255)
# Set the width and the height of the window
(width, height) = (300, 200)
# set the screen fro pygame to the width and height tuple defined above
screen = pygame.display.set_mode((width, height))
# set the name of the pygame project at t... |
class Toy():
def __init__(self,color,age):
self.color= color
self.age= age
self.my_dict= {
'name':'Yoyo',
'has_pets':False
}
def __str__(self):
return f'{self.color}'
def __len__(self):
return 5
def __call__(self):
return(... |
# 4.3
## 4.3.1 Intro to network analysis
import networkx as nx
# create an undirected graph
G = nx.Graph()
# add node:
G.add_node(1)
G.add_nodes_from([2,3])
G.add_nodes_from(['u','v'])
# view nodes
G.nodes()
NodeView((1, 2, 3, 'u', 'v'))
# adding edges takes 2 args, the nodes
G.add_edge(1,2)
G.add_edge('u','... |
#Exercise 1
#A cipher is a secret code for a language. In this case study, we will explore a cipher that is reported by contemporary Greek historians to have been used by Julius Caesar to send secret messages to generals during times of war.
#The Caesar cipher shifts each letter of a message to another letter in the a... |
import usuarios.conexion as conexion
connect = conexion.conectar() # variable connect llamar metodo conectar que esta dentro de coexion
database = connect[0] #indice cero donde eeta la base de datos
cursor = connect[1] #indice uno donde esta el cursor
class Producto:
def _... |
#
# Global settings
#
# Step size for calculation
step = 1/12.
nyears = 14
nstep = int(nyears/float(step))
# Step size for temperature (determines roughly the granularity of reported sensor temperatures)
ts_step = 5 # steps per degree
# time_step_list is a list of each step through the years, for plotting purposes m... |
import unittest
from problem_two import *
class TestPrintDepth(unittest.TestCase):
def test_output(self):
"""
Tests if the value returned from the print_depth function
matchs the expected value.
"""
var1 = {
"key1":1,
"key2":{
... |
def get_salary(hours: int) -> int:
res = hours * 84
if hours > 120:
res += (hours - 120) * 84 * 0.15
if hours < 60:
res -= 700
return res
if __name__ == "__main__":
try:
hours = int(input("Pls input the hours of work:"))
print(f"Salary is {get_salary(hours)}")
e... |
print("To je program za pretvarjanje enot")
kilometri = int(raw_input("Vnesi stevilo kilometrov: "))
conv_fac = 0.621371
milje = kilometri * conv_fac
print("To je " + str(milje) +" milj")
while True:
answer = raw_input("Zelis narediti novo pretvorbo? (yes/no)")
if answer == "yes":
kilometri = int(ra... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# 「Introduction to Computation and Programming Using Python」の§3.3の例題2
def isIn(short_string, long_string):
m = len(long_string)
n = len(short_string)
for i in range(m):
if long_string[i] == short_string[0]:
flag = True
for j in ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# 「Introduction to Computation and Programming Using Python」の§4.1.2の例題
def printName(firstName, lastName, reverse=False):
if reverse:
print lastName + ', ' + firstName
else:
print firstName, lastName
printName('Olga', 'Puchajerova')
printName('Olg... |
def manhattanDistance(p1, p2):
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
with open("6.txt", "r") as f:
coordinates = []
for line in f.readlines():
current = line.rstrip("\n").split(",")
coordinates.append((int(current[0]), int(current[1])))
areaOwned = {c: [0, False] for c in coo... |
import pygame
import math
pygame.init()
BLACK = (0,0,0)
WHITE = (255,255,255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0,0,255)
PI = 3.141592653
done = False
clock = pygame.time.Clock()
size = (700,500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Mr Duguid's Cool Game")
screen.fill(WHITE... |
from turtle import Turtle
class GameBar(Turtle):
def __init__(self):
super().__init__()
self.speed(0)
self.penup()
self.color('white')
self.hideturtle()
self.goto(0, 260)
def set_points(self, tray_left, tray_right):
self.clear()
self.write(f"Pl... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the caesarCipher function below.
def caesarCipher(s, k):
q="abcdefghijklmnopqrstuvwxyz"
w = q.upper()
t = ""
for i in s:
if i not in q and i not in w:
t=t+i
else:
if i not in q:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Development environment:
# - Python 2.7.5 (32-bit)
# - Windows 7 64-bit machine
import json
from pprint import pprint
def getMovieRatings(jsonFile):
""" Reads movie ratings from json file and returns an object """
with open(jsonFile) as ratingsFile:
... |
#
#3. Delete Operation on Array
#
number_array = [4, 5, 2, 7, 9, 13];
# Lets delete the item in the 3rd position of the original array [4, 5, 2, 7, 9, 13];
print("=========== Initial Array =========")
for idex, item in enumerate(number_array):
print(" Array [", idex , "] ", item)
print("=========== Initial ... |
import datetime
class User:
def __init__(self, name, birthday):
self.name = name
self.birthday = birthday
def age(self):
today = datetime.date(2021, 5, 18)
yyyy = int(self.birthday[0:4])
mm = int(self.birthday[4:6])
dd = int(self.birthday[6:8])
dob = da... |
# method to format the list of users
# prints user's title, fan count, likes, and userID
def print_user_data( user_list ):
i = 0
for user in user_list:
print(str(i) + ': ' + user['title'] + " FANS:" + str(user['extraInfo']['fans']) + " LIKES:" + str(
user['extraInfo']['likes']) + " ID:" ... |
import sqlite3 #enable control of an sqlite database
import csv #facilitates CSV I/O
f="discobandit.db"
db = sqlite3.connect(f) #open if f exists, otherwise create
c = db.cursor() #facilitate db ops
#==========================================================
fObj1 = open("peeps.csv")
fObj2 = open("cour... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
from perceptron import Perceptron
f = lambda x:x
class LinearUnit(Perceptron):
def __init__(self,input_num):
Perceptron.__init__(self,input_num,f)
def get_training_dataset():
input_vecs = [[5],[3],[8],[1.4],[10.1]]
labels = [5500,2300,7600,1800... |
import time
from threading import Thread
COUNT = 500_000_000
def countdown(n):
while n > 0:
n -= 1
start = time.time()
t1 = Thread(target=countdown, args=(COUNT//2,))
t2 = Thread(target=countdown, args=(COUNT//2,))
t1.start()
t2.start()
t1.join()
t2.join()
end = time.time()
print("Tempo em segundos:", ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.