text stringlengths 37 1.41M |
|---|
import math
def elfi(array, strict=True):
"""
The ELFI is a simplified method for calculating the
Ethnic Diversity Index.
Accepts a list of decimal percentages, which are used
to calculate the Ethnolinguistic Fractionalization Index (ELFI).
Returns a decimal value as a floating point number.
By default... |
# mattetrener
import random
riktig = 0
feil = 0
print("1. Addisjon")
print("2. Subtraksjon")
print("3. Multiplikasjon")
print("4. Divisjon")
valg = input("Velg regneart")
while True:
if valg in ('1', '2', '3', '4'):
if valg == '1':
a = random.randint(1, 1000)
b = r... |
#import dependencies
import os
import csv
#list of files
row_index = 0
month_counter = 0
sum_revenue = 0
sum_revenue_change = 0
revenues = []
months = []
change_revenues = []
# * The total number of months included in the dataset
with open('Resources/budget_data.csv', 'r') as file:
reader = csv.reader(file)
... |
#this code scrapes bill data for Pennsylvania alumnae using Python, Selenium, and BeautifulSoup
#then imports it to Google Sheets using Pygsheets
#last updated 07/18/2019 by Camille Kirsch, communications intern
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
import pygsheets
i... |
import threading
from time import sleep
class IntervalExec:
def __init__(self, func, interval, args):
self.run = False # Runs as long as this is true
self.func = func # Function to execute
self.interval = interval # Interval in seconds
self.runlock = threading.RLock()
... |
aprovados = [
"Graziela Barroso", "Juliano Moreira", "André Rebouças", "César Lattes","Enedina Alves",
"Machado de Assis", "Ayrton Senna", "Luiz Gamma", "Ruth de Souza", "Nise da Silveira",
"Johanna Döbereiner", "Carolina de Jesus", "Leopoldo Nachbin", "Antonieta de Barros", "Lima Barreto"
]
vagas = in... |
# !/usr/bin/python3
class Employee:
"""Common base class for all employees"""
_emp_count = 0 # private static variable of the class
def __init__(self, name, salary):
# these two are instance variables
self.name = name
self.salary = salary
Employee._emp_count += 1
@s... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
def TwoWayInsertionSort(Data):
first=0 #first、final分别指示Sort中排好序的记录的第1个和最后1个记录的位置
final=0
lens=len(Data)
Sort=[0 for i in range(lens)]
Sort[0]=Data[0]
for i in range(1,lens):
if Data[i]<=Sort[first]: #待插入记录小于Sort中最小值,插... |
fruits = {
"苹果": 12.3,
"草莓": 4.5,
"香蕉": 6.3,
"葡萄": 5.8,
"橘子": 6.4,
"樱桃": 15.8
}
info = {
'小明': {
'fruits': {'苹果': 4, '草莓': 13, '香蕉': 10},
'money': 0
},
'小刚': {
'fruits': {'葡萄': 19, '橘子': 12, '樱桃': 30},
'money': 0
}
}
def mon... |
class Cup:
__height = 0
__volume = 0
__color = ''
__material = ''
def setHeight(self, height):
try:
height = int(height)
except ValueError:
print("请检查输入,要输入数字哦")
else:
if height > 0:
self.__height = height
... |
"""
使用udp完成,在客户端循环的输入单词,得到单词解释.知道摁回车退出查询. 可以满足同时启动多个客户端一起查询
"""
from socket import *
# 查找单词
def find_word(word):
# 打开文件
f = open('dict.txt')
for line in f:
w = line.split(' ')[0]
# 遍历的单词已经大于目标,说明找不到了
if w > word:
break
elif w == word:
f.close()
... |
lista = [124,345,5,72,46,6,7,3,1,7,0]
lista.sort() #ordena crescente
print(lista)
lista.reverse() #ordena descrescente
print(lista)
lista2 = ["bola","abacate","dinheiro"]
lista2.sort() #ordena crescente
print(lista2)
lista2.reverse() #ordena descrescente
print(lista2) |
#! /usr/bin/env python
from optparse import OptionParser #how OptionParser is imported
parser = OptionParser()
parser.add_option('-c', '--cost', dest='cost', type='float')
parser.add_option('-s', '--tax', dest='tax', type='float')
parser.add_option('-t', '--tip', dest='tip', type='float')
(options, args) = parse... |
class multiply:
def square(self,num):
return num* num
class Cube(multiply):
def __init__(self):
pass
def __call__(self,num):
return num*num*num
def square(self,num):
return super().square(num)
cube = Cube()
print(type(cube))
print(cube(5))
print(cube.square(3))
|
#############################################################################
# using built in function
from binarytree import build
def build_binary(items):
print("Using built in module to create binary tree")
btree = build(items)
print(btree)
return btree
def inorder(btree):
print('Using built... |
# # Type range
#
# for i in range(5):
# print(i,end=', ')
# print()
# for i in range(5,10):
# print(i,end=', ')
# print()
# for i in range(5,15,2):
# print(i,end=', ')
# print()
#
# #Перебор используя continue - встречая равенство условия, дальше не идем а возвращаемся на итерацию выше
# for i in 'hello wor... |
# -*- coding: utf-8 -*-
# @Author: wangchao
# @Time: 19-8-26 上午11:47
class Node:
"""
功能:链表节点,以及节点相关操作
"""
def __init__(self, initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setD... |
# -*- coding: utf-8 -*-
# @Author: wangchao
# @Time: 19-8-16 上午10:08
def anagramSolution1(s1, s2):
"""
功能: 乱序字符串检查,'heart'和'earth'就是乱序字符串,为了简单,规定字符串具有相同的长度
实现: 将s2转换成列表alist,检查s1中的每个字符是否存在alist中,如果存在,替换成None
:param s1: 字符串
:param s2: 字符串
:return: bool
"""
alist = list(s2)
pos1 = 0
... |
# -*- coding: utf-8 -*-
# @Author: wangchao
# @Time: 19-8-27 下午2:24
class Node:
"""
功能:链表节点,以及节点相关操作
"""
def __init__(self, initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setDa... |
# -*- coding: utf-8 -*-
# @Author: wangchao
# @Time: 19-9-2 上午11:31
def shortBubblueSort(alist):
"""
功能:短冒泡排序(当列表在某一刻为有序时,则不需要进行循环排序)
实现:
:param alist:
:return:
"""
stop = True
passnum = len(alist) - 1
while passnum > 0 and stop:
# 如果没有交换则认为是有序的,不用再进行循环
stop = Fal... |
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import defaultdict
# Complete the makeAnagram function below.
def makeAnagram(a, b):
a_char_dict = defaultdict(int)
for char in a:
a_char_dict[char] += 1
counter = 0
for char in b:
if a_char_dict[c... |
from abc import ABC, abstractmethod
# Stratyge pattern is very familliar with the state pattern but it has two states
# That we can change depinding in which we choice, the pattern depends on polyphenism
class MessageType(ABC):
@abstractmethod
def typyMessage(self):
pass
class Message... |
#! /home/b51816/Python-3.5.1/python
### HAN NUO Tower
def move(n,a,b,c):
if n==1 :
print(a,"-->",c)
else:
move(n-1,a,c,b)
move(1,a,b,c)
move(n-1,b,a,c)
A = 'A'
B = 'B'
C = 'C'
move(4,A,B,C) ## exmaple for hanoi tower
|
print("Εισάγετε τις 3 τιμές με τις οποίες θα δουλέψουμε.")
a = input("Καταρχήν εισάγετε την 1η τιμή: ")
a = float(a)
b = input("Την 2η τιμή: ")
b = float(b)
c = input("Και τελικά την 3η τιμή: ")
c = float(c)
def elenhos_trigonou(alfa, vita, gamma):
if alfa <= 0 or vita <= 0 or c <= 0:
return -1
else:
... |
#Creating/Opening a netCDF file
'''
There are many options for working with NetCDF files
in Python. In this example we have chosen to highlight
the use of the netCDF4-python module.
The netCDF4-python module is useful because:
• It implements the basic “classic” model as well as
more advanced features.
• I... |
# -*- coding: utf-8 -*-
a = int(input())
if a % 3 == 0:
print("YES")
else :
print("NO")
|
# -*- coding: utf-8 -*-
N = int(input())
print(int(N * 2))
|
import requests
import pandas as pd
import json
import pickle
import numpy as np
# C. Creating a dataframe for Abortion policy from CSV file. Data obtained from this PDF: https://www.reproductiverights.org/sites/crr.civicactions.net/files/documents/AbortionMap_Factsheet_2013.pdf
''' scale:
0 (abortion crim... |
from random import choice
class RandomWalk:
def __init__(self,num_points =5000):
self.num_points = num_points
self.x = [0]
self.y = [0]
def fill_walk(self):
while len(self.x) < self.num_points:
x_direction = choice([1,-1])
x_distance = c... |
#!/usr/bin/env python
import sys
nodec = 'aeiouyAEIOUY- \'!.öåäÅÄÖ'
def usage():
print('Usage:')
print(' ./Rovarspraket [-d] "<input string>"')
print(' Add -d flag to decode message')
print('Example:')
print(' ./Rovarspraket "I\'m speaking Robber\'s language!"')
sys.exit()
def encod... |
from Tkinter import *
import ttk
def calculate(*args):
try:
value = float(year.get())
x.set(value * 1)
except ValueError:
pass
root = Tk()
root.title("USD to Pounds")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
m... |
def isPrime(n):
""""precondition n is a nonnegative integer
postcondition: return True if n is prime and False otherwise."""
if n < 2:
return False;
if n % 2 == 0:
# return False
return n == 2
k = 3
while k*k <= n:
if n % k == 0:
return False
... |
from bs4 import BeautifulSoup
import urllib2
req = urllib2.Request("http://adventuresintechland.com/a-web-scraper-that-doesnt-completly-suck/")
response = urllib2.urlopen(req)
the_page = response.read()
soup = BeautifulSoup(the_page)
text = soup.findAll("html")
print text[0].text |
from datetime import datetime
now = datetime.now()
months = {1 : 0, 2 : 31, 3 : 59, 4 : 90, 5 : 120, 6 : 151, 7 : 181, 8 : 212, 9 : 243, 10 : 273, 11 : 304, 12 : 334}
date = raw_input("What is your birthday? (mm/dd/yyyy) ")
month = int(date[:2])
day = date[3:5]
year = date[6:]
days = ((now.year - int(year)) * 365)... |
#time for wait
import time
print """
================
Cookie Country!
================
"""
time.sleep(2)
print "You are King Cookie!"
time.sleep(2)
print ""
print "Your nemisis, King Rasin, is building an army!"
time.sleep(4)
print ""
print "Your duty as king is to defend your land!"
time.sleep(4)
print ""
print "Buil... |
#Answering the question: Which NBA teams have the most distance between them?
#The WolframAlpha API returns the miles between two locations.
# Credit to https://github.com/myzeiri/Distances-Between-Cities
import urllib.request, urllib.error, urllib.parse
from xml.etree import cElementTree as ET
import pandas as pd
app... |
import datetime
input_second = int(input("Pleas enter second: "))
time = str(datetime.timedelta(seconds = input_second))
print("Time =", time) |
nterms=int(raw_input())
n1=1
n2=1
count=0
if nterms==1:
print n1,
else:
while count<nterms:
print n1,
nth=n1+n2
n1=n2
n2=nth
count+=1
|
# prob-decryption.py
#
# WARNING! THIS IS POSSIBLY *NOT* SECURE.
# DO NOT USE TO ENCRYPT SENSITIVE INFO.
#
# Decrypts an encrypted file.
#
# written by Z. Henderson
def decipher(ciphertext, p, q):
if ord(ciphertext[-1]) == 10:
ciphertext = ciphertext[:-1] # removes end-of-text newline characte... |
import time
real_password = "2687"
def check_password(password):
if len(password) != len(real_password):
return False
for x, y in zip(password, real_password):
time.sleep(0.1) # Simulates the wait time of the safe's mechanism
if int(x) != int(y):
return False
return T... |
#!/usr/bin/env python
# coding: utf-8
# This is a data set thet ahas been aquired from kaggle. As commercial banks receive alot of applications for credit cards and many of them get rejected due to various reasons. Here in this project i have tried using machine learning to predict the approval of credit cards.
# In[... |
"""
Convenient File handling utilities.
This module has some file handling functions that are available for convenience or to jog your
memory.
In your implementation of the cache, you may choose to use all, some or none of the functions
listed here.
"""
from pathlib import Path
def write(path: Path, b: bytes) -> N... |
import time
tStart = time.time()
def C(n,r):
return int(Fact(n)/((Fact(r))*Fact(n-r)))
def Fact(num):
if num == 0:
return 1
if num < 0:
return -1
if num != 1:
num = num * (Fact(num-1))
return num
count = 0
for a in range(100):
for b in range(a):
#print (a+1, " ... |
import time
import itertools
tStart = time.time()
def isPrime(num):
'checks if num is a prime number'
if num < 0:
return False
if num == 1:
return False
result = True
currValue = 2
maxValue = num/2
while currValue <= maxValue:
if num % currValue == 0:
res... |
import time
tStart = time.time()
def isPrime(num):
'checks if num is a prime number'
if num < 0:
return False
if num == 1:
return False
result = True
currValue = 2
maxValue = num/2
while currValue <= maxValue:
if num % currValue == 0:
result = False
... |
import time
tStart = time.time()
def ConvertRomanNumeralToNumber(roman_numeral):
number_result = 0
roman_numerals = {
1:"I", 4:"IV", 5:"V", 9:"IX",
10:"X", 40:"XL", 50:"L",
90:"XC", 100:"C", 400:"CD",
500:"D", 900:"CM", 1000:"M"}
# Iterate through the roman numerals. But y... |
import sys
# SearchGraph.py
#
# Implementation of iterative deepening search for use in finding optimal routes
# between locations in a graph. In the graph to be searched, nodes have names
# (e.g. city names for a map).
#
# An undirected graph is passed in as a text file (first command line argument).
#
# Usage: pyth... |
"""
Example script for how to use the module neurons.py
"""
import neurons
import numpy as np
# Global parameters, must be the same for all created neurons
sim_time = 5
dt = 0.001
# Create an array of 100 excitatory Poisson neurons
exc_input = np.array([neurons.PoissonNeuron(sim_time, dt, 'exc') for _ in range(10)])
... |
#Create a character array that will hold the various attributes that a user can pick from when chooising their
#career path.
print "Chooise five attributes that you either possess are are interested in."
#An array that holds the attributes that will be displayed for the user to choose from
attributes = ["patience", "c... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
else:
return max(self.maxDepth(r... |
# -----Question 1-----
# Now you are a microbiologist. Initially( when t=0), you have only one bacterium. To perform an important research, you need *exactly* N bacteria.
#
# Every alive bacteria will clone itself every second. Hence, the number of alive bacteria will doubled every second. At every second, you can sele... |
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
ssum = 0
ans = []
for num in nums:
ssum += num
ans.append(ssum)
return ans
# Time: O(n)
# Space: O(1)
# Runtime: 40 ms, faster than 62.06% of Python3 online submissions for Running Sum of 1d... |
import unittest
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
# stack = []
# dummy = ListNode(-1)
# dummy.next = head
# cur = dummy.nex... |
import operator
class Solution:
def pop_overlap(self, a, b):
if b[0] <= a[1] <= b[1] and a[0] <= b[0] <= a[1]:
a = [a[0], b[1]]
return a
elif a[0] <= b[0] <= a[1] and a[0] <= b[1] <= a[1]:
a = [a[0], a[1]]
return a
else:
return ()
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
def processNode(node, prefix):
if node != N... |
import math as m
class Solution:
def climbStairs(self, n: int) -> int:
total = 0
a = 0
while n-a>=0:
total += int(m.factorial(n)/(m.factorial(a) * m.factorial(n-a)))
a += 1
n -= 1
return total
# Time: O(n^2) # Assuming factorial is O(n) # Otherwis... |
'''
Created on Jun 17, 2016
@author: KatherineMJB
'''
import numpy as np
def shuffle_in_unison(a, b):
# this method shuffles the two arrays according to the same randomized
# index
assert len(a) == len(b)
shuffled_a = np.empty(a.shape, dtype=a.dtype)
shuffled_b = np.empty(b.shape, dtype=b.dtype)
... |
## Spark
Before you turn this problem in, make sure everything runs as expected. First, restart the kernel (in the menubar, select Kernel → Restart) and then run all cells (in the menubar, select Cell → Run All). You can speak with others regarding the assignment but all work must be your own.
### This is a 20 po... |
from operator import attrgetter
class Employee():
def __init__(self, name, age ,salary):
self.name = name
self.age = age
self.salary = salary
def __repr__(self):
"""[A função __repr__ retorna uma representação do objeto,
ela deve retornar uma string, caso contr... |
# need depth limit
import random;
# why this works, I don't know. DON'T CHANGE
nodes = 0
leaves = 0
toPrint = []
toPrintList = []
nodeList = []
# limits
minLeaves = 90
maxLeaves = 110
# class definitions
class Node:
maxDepth = 10 # change as necessary
def __init__ (self, operation, value, depth, c... |
from tkinter import *
from time import *
# Function returns which shape to print
def get_shape(currentShape):
if currentShape == "x":
currentShape = "o"
elif currentShape == "o":
currentShape = "x"
return currentShape
def validate_click(frame) :
for x in frame._history_x :
if x == frame.square_id ... |
#####################################
# python sorting advanced tutorials #
#####################################
# [I]. sorting with key func
# 1. how about records with equal keys, what would be the order of sorting?
# Ans: retain the input order sequence
strings = ['aa', 'zz', 'OO', 'AA', 'Z']
print(sorted(strings,... |
class Human :
def __init__(self,name, age):
self.name = name
self.age= age
print (f" Name is {name} age is {age}")
h1=Human("Shishir",20) |
# -*- coding: utf-8 -*-
'''
Created on 5/10/2014
Ejercicio 7
Calcular e imprimir el producto 1*2*3*4*5*...*20
@author: Luismi
'''
i= 1
for j in range(1,20):
i*=j
print i
def producto(x,y):
return x*y
print reduce(producto,range(1,20))
|
# -*- coding: utf-8 -*-
'''
Created on 12/10/2014
Ejercicio 5
Escriba un programa que permita crear dos listas de palabras y que, a continuaci�n,
elimine de la primera lista los nombres de la segunda lista.
NOTA: Se introduce, a modo de ejemplo, el manejo de excepciones, para hacer el
ejercicio más fácil.
@... |
# -*- coding: utf-8 -*-
'''
Created on 21/10/2014
@author: Luismi
'''
class B(object):
'''
classdocs
'''
def __init__(self, val1):
'''
Constructor
'''
#print val1
class C(object):
def __init__(self):
'''
Constructor
'''
... |
# -*- coding: utf-8 -*-
'''
Created on 7/11/2014
@author: Luismi
Crear un m�dulo para validaci�n de contrase�as. Dicho m�dulo, deber� cumplir con los siguientes criterios de aceptaci�n:
La contrase�a debe contener un m�nimo de 8 caracteres.
Una contrase�a debe contener letras min�sculas, may�sculas, n�mero... |
#!/bin/env python3
from grid import Grid
import time
"""
Game engine.
Contains the different data structures required.
Computes the future state of the sstructure.
"""
class Engine:
def __init__(self, grid_size):
"""
Constructor of an engine
"""
self.current_grid = Grid(grid_size)
... |
dict1 = {'python': 95, 'java': 99, 'c': 100}
# 字典长度为多少
print(len(dict1))
# 修改'java'这个key对应的value值为98
dict1['java']=98
print(dict1)
# 删除 c 这个key
del dict1['c']
print(dict1)
# 增加一个key-value对,key值为php,value为90
dict1['php'] = 90
print(dict1)
# 获取所有key值,存储在列表里
print(dict1.keys())
# 获取所有value值,存储在列表里
print(dict1.values())
# ... |
import socket
if __name__ == '__main__':
# 创建tcp服务端套接字
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置端口号复用,让程序退出端口号立即释放
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
# 给程序绑定端口号
tcp_server_socket.bind(("", 8989))
# 设置监听
#... |
# ######### Guideline #########
# 1. Candidate splits for nominal features should have one branch per value of the nominal feature.
# The branches should be ordered according to the order of the feature values listed in the ARFF file.
# (construct_dt)
# 2. Candidate splits for numeric features should use threshol... |
import anneal
import time
from typing import List, Tuple
# Type aliases
Flow = List[List[int]]
Distance = List[List[int]]
Population = List[Tuple[List[int], int]]
#Globals
POP_SIZE = 20
def score(flow_matrix: Flow,
dist_matrix: Distance,
permutation: List[int]) -> int:
""" Returns the cost ... |
class Jar:
'''Represents a jar'''
def __init__(self, size):
'''Jar(size) -> Jar
Constructs a Jar
size: int giving size of jar'''
self.size = size
self.water = 0 # starting jar is empty
def __str__(self):
'''str(Jar) -> str
Returns a string giving th... |
import random
class DominoTile:
def __init__(self,left,right):
self.left = left
self.right = right
def __str__(self):
return(str(self.left) + ' ' + str(self.right))
def is_match(self,other):
return (self.left == other.left) or (self.left == other.right) or (self.right ... |
# https://leetcode.com/problems/shortest-distance-to-a-character/
S = "loveleetcode"
C = "e"
class Solution(object):
def shortestToChar(self, S, C):
"""
:type S: str
:type C: str
:rtype: List[int]
"""
distance_to_char_list = []
indices_character = []
... |
# https://leetcode.com/problems/middle-of-the-linked-list/
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def middleNode(self, head):
"""
:type head: ListNode
:rtype: List... |
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if (n == 1):
return "1"
if (n == 2):
return "11"
num_str = "11"
for i in range(3, n + 1):
num_str += '$'
l = len(num_st... |
#! python3
import os
import file_organize
import file_rename
def type_input(inputted_command):
"""
type_input takes in a command and calls the corresponding functions from
file_organize and file_rename
:param inputted_command: any of 'run 'organize' 'quit'
:return: calls the functions that or... |
def add(a,b):
print "ADDING %d + %d" %(a,b)
return a + b
def substract(a, b):
print "SUBSTRACTING %d - %d" % (a,b)
return a - b
def multiply(a,b):
print "DIVIDING %d / %d" % (a, b)
return a * b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
print "Let's do some math with just functions!"
... |
people = 20
cats = 30
dogs = 15
if people < cats:
print "Too manu cats! The world is doomed!"
if people > cats:
print "Not many cats The wordl is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs:
print "The world is dry!"
dogs += 5
if people >= dogs:
print "People are greater than ... |
print("podaj liczbę całkowitą")
x = int(input())
if(x%2==0):
print("parzysta")
else:
print("nieparzysta")
print("sposób 2")
print("podaj liczbę całkowitą")
lst = ["parzysta", "nieparzysta"]
x = int(input())
y=x%2
print(lst[y])
|
import os
print("podaj liczbę kolumn")
n=int(input())
print("podaj liczbę wierszy")
m=int(input())
for x in range(1, m+1):
z=''
for y in range(1, n+1):
z+="\t"
z+=str(x*y)
print(z)
os.system("PAUSE")
|
import math
def rd(a,b):
if(int(b)==1):
return (a*180/math.pi)
else:
return ((a/180)*math.pi)
print("co chcesz przekonwertować")
print("1-radiany na stopnie")
print("2-stopnie na radiany")
x=int(input())
print("podaj wartość w wybranej uprzednio jednostce")
y=float(input())
print(rd(y,x))
|
x = int(input())
y = int(input())
temp = x
x = y
y = temp
print('{}'.format(x))
print('{}'.format(y))
|
a=int(input())
if (a%2)==0:
print ("Even")
elif (a%2)!=0:
print ("Odd")
else:
print ("invalidop")
|
import random
alphabets ='qwertyuiopasdfghjklzxcvbnm'
signs = ';:-_+[{]}\|.><,'
number = '1234567890'
while True:
length = False
command= input('Write Password Type (type help for commands)>> ')
if command == 'help':
print('number - only numerical password \' alphabet - for only word password \' ... |
import numpy as np
import matplotlib as mpl
puntos = []
for i in range(10):
x0 = np.random.randint(-10,10,size=2).tolist()
x1 = np.random.randint(-10,10,size=2).tolist()
puntos.append([x0,x1])
print (puntos)
def recta(a1,a2):
m = (a1[1]-a2[1])/(a1[0]-a2[0])
b = m*a1[0] + a2[1]... |
class UniversalContainer:
def __init__(self): # constructor for empty container
self.capacity_ = 1 # we reserve memory for at least one item
self.data_ = [None]*self.capacity_ # the internal memory
self.size_ = 0 # no item has been inserted yet
def size(self):
return self.si... |
import unittest
from codalab.lib.formatting import size_str
class SizeStrTest(unittest.TestCase):
def test_bytes_formatting(self):
"""
The number of bytes should be returned as a string.
If include_bytes is True, 'bytes' should be appended to the return value.
"""
# < 100 b... |
"""
Run the math adventure.
How this game works.
You, the player, will spawn at the middle of the math world and need to find
the randomly generated portal at the corner by navigating through this
dimension by typing in up, down, left or right when the player is prompted with
the question. There are also chests and ma... |
#!/usr/bin/env python
# _*_ coding:UTF-8 _*_
"""
_title_ = ''
_author_ = '♞Demons♛'
_date_ = '2020-01-12'
"""
listArray = ['Michael', 'Bob', 'Tracy']
print(listArray)
# 获取数组的长度
print(len(listArray))
# 获取数组中单个元素,下标从0开始
print(listArray[0])
print(listArray[1])
print(listArray[2])
# 获取数组最后一个元素,使用下标-1
print(listArray[-1])
... |
#!/usr/bin/env python
# _*_ coding:UTF-8 _*_
"""
_title_ = ''
_author_ = '♞Demons♛'
_date_ = '2020-01-10'
"""
print('first python print')
# 括号中有多个参数时默认使用空格分隔
print('first', 'second', 'third')
# 支持多种类型参数的拼接
print('string', 2, 8.6)
print(2)
print(3 + 5)
print(3 + 5.80)
print('100 + 200 =', 100 + 200)
# 从控制台接收输入值,赋值给变量na... |
# def binSearch(numbers, element):
# low = 0
# length = len(numbers)
# # print(length)
# high = length - 1
# mid = numbers[int((length-1)/2)]
#
# if element < numbers[mid]:
# numbers = numbers[:mid]
#
# if element > numbers[mid]:
# numbers = numbers[mid:]
#
# if element =... |
# Insertion Sort
# Arrange data in Ascending Order
def insertionSort(data):
for i in range(1, len(data)):
key = data[i]
j = i - 1
while j >= 0 and data[j] > key:
data[j+1] = data[j]
j -= 1
data[j + 1] = key
numbers = [45, 22, 11, 23, 19, 10, 33, 12, 55, ... |
#!/usr/bin/python3
def print_sorted_dictionary(a_dictionary):
for i in sorted(a_dictionary):
print(str(i) + ": " + str(a_dictionary[i]))
|
#!/usr/bin/python3
'''Module for the method save_to_json_file'''
import json
def save_to_json_file(my_obj, filename):
'''Method from json to file'''
with open(filename, 'w') as filename:
json.dump(my_obj, filename)
|
#!/usr/bin/python3
def update_dictionary(a_dictionary, key, value):
if key is a_dictionary:
for i in a_dictionary:
if i == key:
a_dictionary[i] = value
else:
a_dictionary[key] = value
return a_dictionary
|
"""
Code for compressing and decompressing using Huffman compression.
"""
from assignments.a2.starter.nodes import HuffmanNode, ReadNode
class Queue:
''' Represent a FIFO queue.
'''
def __init__(self):
''' (Queue) -> NoneType
Create and initialize new queue self.
'''
self... |
# Write a function that takes two base-26 numbers
# in which digits are represented by letters with
# A=0, B=1, … Z=25 and returns their product using
# the same notation. As an example, CSGHJ × CBA = FNEUZJA.
#
# Your task is to write the base-26 multiplication function.
#
# Try to be very efficient in your code!
#
# ... |
# You are to write a function that displays the numbers
# from 1 to an input parameter n, one per line, except
# that if the current number is divisible by 3 the function
# should write “Fizz” instead of the number, if the current
# number is divisible by 5 the function should write “Buzz”
# instead of the number, and ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.