text stringlengths 37 1.41M |
|---|
import tkinter as tk
def button_clicked():
my_label.config(text=user_input.get())
print(user_input.get())
window = tk.Tk()
window.title("My First GUI Program")
window.minsize(width=500, height=300)
window.config(padx=20, pady=20) # how to add padding
my_label = tk.Label(text="I am a label", font=("Arial",... |
# -*- coding: utf-8 -*-
# создаём первый супер-класс
class mainClass:
arg1 = 'This is argument 1 from class mainClass;'
arg2 = 'This is argument 2 from class mainClass;'
def ext_1(self):
return 'This if method ext_1 from class mainClass.'
# создаём объект суперкласса
main_class ... |
#Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user.
#Start the program
#Get number
number = input("Enter a number: ")
mod = number % 2
#Validate the type of number if is odd and even
if mod > 0:
print("You insert an odd number")
else:
print... |
#-------------------------------------------------------------------------------------------------------------------------------------
# Program Objective: Create an automobile class that will be used by a dealership as a vehicle inventory program.
# The following attributes are the automobile class:
# -private string ... |
class HashTableNode:
def __init__(self, word ,vector, next):
self.word = word
self.vector = vector
self.next = next
class HashTable:
def __init__(self, table_size, alpha_value):
self.table = [None] * table_size
self.alpha_value = alpha_value
def insert(self,k,vector, funcselect):
loc = sel... |
n = int(input("Nhap vao so n:"))
S = 0
for number in range(n+1):
S += number
print(S) |
def sort_cards(stuff):
"""Sorts a list of cards by ascending values."""
cards = {
'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13
}
return sorted(stuff, key=cards.get)
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 26 19:30:26 2020
@author: User
"""
import random
while True:
guess = int(input('guess(1~20):'))
count = 0
a = random.randint(1,20)
if guess==a:
print('bingo!')
break
else:
print('wrong!')
if guess > a:
... |
'''Sprint Challenge Unit 3 Sprint 1 - Part 4 Class report'''
from random import randint, sample, uniform
from acme import Product
ADJECTIVES = ['Classic', 'Shiny', 'Explosive', 'New', 'Improved']
NOUNS = ['Anvil', 'Catapult', 'Tunnel', 'Dynomite', 'TNT']
def generate_products(num_products=30):
"""Make random pr... |
prices = [0, *map(int, input().split())]
trucks = [tuple(map(int, input().split())) for _ in range(3)]
starts = [t[0] for t in trucks]
ends = [t[1] for t in trucks]
price = 0
curr_trucks = 0
for time in range(1, max(ends) + 1):
curr_trucks += starts.count(time)
curr_trucks -= ends.count(time)
price += pric... |
CONFUSING_TRANS = str.maketrans("BGIOQSUYZ", "8C1005VV2")
def translate(s):
return s.translate(CONFUSING_TRANS)
def char_val(c):
return "0123456789ACDEFHJKLMNPRTVWX".index(c)
def dec_to_char(d):
return "0123456789ACDEFHJKLMNPRTVWX"[d]
def check_digit(s):
coeff = (2, 4, 5, 7, 8, 10, 11, 13)
chec... |
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not len(matrix) or not len(matrix[0]):
return False
for row in matrix:
if row[-1] < target:
... |
def does_react(a, b):
return a != b and a.lower() == b.lower()
def react(l):
changes = True
while changes:
nl = []
changes = False
i = 0
while i < len(l):
if i < len(l) - 1 and does_react(l[i], l[i + 1]):
i += 2
changes = True
... |
from itertools import permutations
n = int(input())
smallest = None
for p in permutations(str(n)):
p = int(''.join(p))
if p > n:
if smallest is None:
smallest = p
smallest = min(smallest, p)
print(smallest if smallest is not None else 0)
|
def gen_digits():
digits = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
digits += ["eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"]
for t in ["twenty", "thirty", "forty", "fifty", "sixty", "seventy",... |
s = input()
i = 1
while s != "END":
mids = s.split('*')[1:-1]
if len(set(mids)) <= 1:
print(i, "EVEN")
else:
print(i, "NOT EVEN")
i += 1
s = input()
|
from collections import deque
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = deque()
open_to_close = {'{': '}', '[': ']', '(': ')'}
for b in s:
if b in open_to_close:
stack.append(open_to_close[b])
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2, carry=0):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
... |
def dist(p1, p2):
return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5
def main():
order = [None] * 9
for i in range(3):
for j, n in enumerate(map(int, input().split())):
order[n - 1] = (i, j)
print(sum(dist(a, b) for a, b in zip(order, order[1:])))
if __name__ == '__main__... |
class Category:
def __init__(self, reqs, contains):
self.reqs = int(reqs)
self.contains = set(contains)
def main():
f = input()
while f != '0':
ncourse, cats = map(int, f.split())
categories = []
courses = set(input().split())
for _ in range(cats):
... |
N = int(input())
while N:
first = [int(input()) for _ in range(N)]
second = [int(input()) for _ in range(N)]
second_to_first_pairs = {s: f for s, f in zip(sorted(second), sorted(first))}
redone_second = [None]*N
for s in second:
f_equiv = second_to_first_pairs[s]
f_ind = first.index... |
from math import pi, sin, cos
T = int(input())
for _ in range(T):
M = int(input())
ang, x, y = pi/2, 0, 0
for _ in range(M):
angle, dist = map(float, input().split())
ang += angle * pi/180
x += cos(ang) * dist
y += sin(ang) * dist
print(x, y)
|
class Node:
def __init__(self, name):
self.name = name
self.connected = []
self.color = None
def main():
N = int(input())
items = [input() for _ in range(N)]
nodes = {name: Node(name) for name in items}
M = int(input())
for _ in range(M):
a, b = input().spl... |
def main():
x, y = int(input()), int(input())
print(get_quad(x, y))
def get_quad(x, y):
if y > 0:
if x > 0:
return 1
else:
return 2
else:
if x < 0:
return 3
else:
return 4
if __name__ == '__main__':
main()
|
from math import cos, sin, radians, hypot
def walk(point, direction, steps):
return point + (direction * steps), direction
def turn(point, direction, degrees):
return point, direction * complex(cos(radians(degrees)),
sin(radians(degrees)))
COMMANDS = {
'walk': walk,
... |
from math import pi, acos
def strand_length(r, h):
return 2 * (h ** 2 - r ** 2) ** 0.5
def circle_ratio(r, h):
return 1 - (acos(r / h) / pi)
def string_length(r, h, s):
strand = strand_length(r, h)
circle_len = circle_ratio(r, h) * 2 * pi * r
return (circle_len + strand) * (1 + s/100)
def main()... |
from src.ingredient import Ingredient
'''
Inventory: a class used to store inventory.
'''
### add minimum amount to sell
class Inventory(object):
def __init__(self):
self._ingredients = {} # dict<Ingredient>
# add new ingredients to the inventory
# ingredients to be created first (aggregatio... |
typeword = eval(input("word to translate into pig latin? "))
firstletter = typeword[0]
restofword = typeword[1:]
piglatinword = restofword + firstletter + "ay"
print (piglatinword)
|
i = 7
while i > 2:
if i == 5:
first = 10
i -= 1
print(first)
|
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#Pull data from minis
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
# Create tensor x as value input, 28x28 = 784 pixel -> varible x is vector of 784 input feature, we set none because we don't know length of data,numbe... |
# Defining class inbuilt listnode
class ListNode:
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):# Constructor
self.head = None
def getSize(self):
curr = self.head
s = 1
while curr.next is not None:
cur... |
##
# date:20170324
# Use : count the face numbers
# Input: rectroiall.txt
##
import os,sys
def get_count_face(filename):
no_face_count = 0
face_count = 0
f = open(filename)
filelines = f.readlines()
for line in filelines:
imginfo = line.strip().split()
#print line
facenum = int(imginfo[1])
if facenum ... |
# This program searches Google Drive and DropBox to find files matching the hashes provided
# Author: Eric Scherfling
# Version: 1.0
import googledrive_seacher
import dropbox_searcher
import argparse
import os
import hashlib
import json
def main():
parser = argparse.ArgumentParser()
search = parser.add_argume... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
def ridge_regression(y, tx, lambda_):
#Ridge regression using normal equations
# y: vector of outputs (dimension N)
# tx: matrix of data (dimension N x D), such that tx[:, 0] = 1
#lambda_: regularization parameter
N,D = tx.shape
... |
import sys
line = ''.join(sys.stdin.readlines())
stop = ['.', '?', '!']
prev = '.'
a = ord('a')
z = ord('z')
A = ord('A')
Z = ord('Z')
def isletter(ch):
return a <= ord(ch) <= z or A <= ord(ch) <= Z
def issmall(ch):
return a <= ord(ch) <= z
count = 0
first = None
for i in range(len(line)):
ch = line[i]
if is... |
# Julius Caesar Act 4, Scene 3, 218–224
brutus_speech = "There is a tide in the affairs of men \nWhich, taken at the flood, leads on to fortune; \nOmitted, all the voyage of their life \nIs bound in shallows and in miseries. \nOn such a full sea are we now afloat, \nAnd we must take the current when it serves, \nOr ... |
import re
def find_vowel_names(input_list):
"""
Given an iterable, return number of lines that
match "name,gender,count", where name starts and ends
with a vowel.
"""
vowels = re.compile(r"^[aeiouAEIOU][a-zA-Z]*[aeiouAEIOU],[FM],\d+$")
vowel_names = []
for line in input_list:
... |
import csv
from sys import argv, exit
import cs50
# Connecting the db file to our python code
db = cs50.SQL("sqlite:///students.db")
# Prompting the user for enough command line arguments
if len(argv) != 2:
print("misssing command line arguments")
exit(1)
# Opening the csv file for reading
with open(argv[1],... |
'''
Create a class Employee that will take a full name
as argument, as well as a set of none, one or more keywords.
Each instance should have a name and a lastname attributes plus
one more attribute for each of the keywords, if any.
'''
class Employee:
def __init__(self, full_name, *args, **k... |
# -*- coding: utf-8 -*-
'''
一次元の特徴量に対して、EM法(Expectation–Maximization Algorithm)を用いて、混合ガウス分布を当てはめる
Usage: $ python modling.py
modeling.main(data,N)
・対数尤度あってるのか?
・BICの実装
'''
import math
import csv
import random
import numpy as np
import matplotlib.pyplot as plt
import matplotli... |
'''
Тут будет тело программы
'''
class Enigma():
def encrypt_by_number(self,text,key):
'''
Зашифровывает текст методом Цезаря
'''
text = list(text)
new_text = []
for i in text:
i=ord(i)
i+= int(key)
if i>= 65536:
i... |
def main():
print nested_sum([[1,2,3],[4,5,6,[7,8,9]])
def nested_sum(t):
x = 0
for val in t:
if type(val) == int:
x += val
else:
x += nested_sum(val)
return x
def remove_duplicates(t):
res = []
for i in range(len(t)):
if t[i] not in res:
res.append(t[i])
return res
if __name__ == '__main__': ... |
from collections import Counter
def mkwrdlst(inputfile):
"""
Makes a list of all words from text file
inputfile: plain text file
output: list of strings
"""
fin = open(inputfile)
words = []
for line in fin:
w = line.strip()
words.append(w)
return words
def eightle... |
"""Created as a solution to an excersize in
thinkpython by Allen Downey
Written by Brooks
Draws a Koch curve of given length
"""
from swampy.TurtleWorld import *
world = TurtleWorld()
bob = Turtle()
bob.delay = 0.01
def draw(t, length, n):
if n == 0:
return
angle = 50
fd(t, length*n)
lt(t, angle)
draw(t,... |
student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
total_height = 0
number_of_students = 0
for height in student_heights:
number_of_students += 1
total_height += height
avarage_height = round(total_height / nu... |
"""
CSV:
Name,Alter,Geschlecht
Susanne, 42, w
Kurt, 27, m
Susanne ist 42 Jahre alt und weiblich
Kurt ist 27 Jahre alt und männlich
...
<file>.readlines()
<string>.split()
"""
with open("mitglieder.csv", "r") as member_file:
members = member_file.readlines()
for x in range(1, len(members)): # anstelle von member... |
def check_upc(string):
rev = string[::-1]
sum_odd = 0
sum_even = 0
for i in range(len(rev)):
if i % 2 == 0:
sum_even += rev[i]
if i % 2 == 1:
sum_odd += rev[i] * 3
total = sum_even + sum_odd
# if total % 10 == 0:
# return True
# else:
... |
# Create a list.
elements = []
# Append empty lists in first two indexes.
elements.append([])
elements.append([])
# Add elements to empty lists.
elements[0].append([1, 2])
elements[0].append(2)
elements[1].append(3)
print elements[0]
elements[1].append(4)
# Display top-left element.
print(elements[0][0][0])
# Disp... |
import numpy as np
def f(x):
s=x**2+x+1
return s
def F(x):
s=x**3/3+x**2/2+x
return s
x=[0,1]
quad=(1/2)*(f(x[0])+f(x[1]))
print('approximation with Trapezontial rule :', quad)
print('real solution of integration : ', F(1)-F(0))
|
def has_redundant(s):
stack = [0]
for c in s:
if c == '(':
stack.append(0)
elif c == ')':
if stack.pop() == 0:
return True
else:
# print stack[-1]
stack[-1] += 1
# Treat (expr) as redundant
return stack.pop() == 0
d... |
'''
https://www.journaldev.com/15911/python-super
'''
import socket
import random
class NetConnect:
def __init__(self,hostname,port):
self.hostname = hostname
self.port = port
def set_hostname(self,hostname):
self.hostname = hostname
def set_port(self,port):
self.port = po... |
'''
1) Write a Python program somewhat similar to http://www.py4e.com/code3/json2.py. The program will prompt for a URL, read
the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the
sum of the numbers in the file and enter the sum below: Here are two files ... |
"""
SimpleSymbols(str)
Input:"+d+=3=+s+"
Output:true
Input:"f++d+"
Output:false
"""
import re
import random
def SimpleSymbols(str):
alpha_str = "abcdefghijklmnopqrstuvwxyz"
if len(str) < 3:
return False
if (str[0] in alpha_str) or (str[-1] in alpha_str):
return False
for letter in ra... |
'''
Unit test suite for following functions
1. SimpleSymbols
2. Replace every letter in the string with the letter following it in the alphabet
(ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this
modified string.
3. Given a String of length S, reverse t... |
from operator import itemgetter
def sort_skills(skills, skill_count):
"""
Given a list of skills, sort them by their confidence level
in descending order. Cleans up irrelevant skills
:param skills: list of skill objects, each with a confidence value
:return: sorted list of skills, with irrelevant ... |
"""
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
For example,"egg" and "add" are isomorphic, "foo" and "bar" are not.
"""
# My thought process:
# (0) Check that strings are the same length. Else False
# (1) walk down the strin... |
"""
Given a singly linked list where elements are sorted in ascending order,
convert it to a height balanced BST.
"""
# Questions I would have had:
# (1) am I get the number of elements?
# Thoughts:
# (1) Use a Red-black tree?
# (2) Do insert, followed by a tree rotation?
# (3) Track length when I insert, then rotate... |
# Часть 1 - присваивание и вывод переменных
a = 10
b = 20
c = 100
d = 'Часть 1 - присваивание и вывод переменных'
print(d)
print('Переменная a =', a, ';', 'Переменная b =', b, ';', 'Переменная b =', c)
# Часть 2 - запрос переменных у пользователя
e = 'Часть 2 - запрос переменных у пользователя'
print(e)
name = input('... |
class A:
def __init__(self, a):
self.a = a
def __str__(self):
return "A:"+str(self.a)
class B:
def __init__(self, a):
self.a = a
def __str__(self):
return "B:"+str(self.a)
class C(A,B):
def __init__(self, a, b, c):
A.__init__(self,a)
B.__init__(self,b)
self.c = c
def __str__(self):
return "{}... |
class Person:
def __init__(self, id, name):
self.id = id
self.name = name
def __str__(self):
return "ID: {}, Name: {}".format(self.id, self.name)
class Employee(Person):
def __init__(self, id, name, dept, job):
super().__init__(id, name) #usage of super
self.dept = dept
self.job = job
def __str__(sel... |
class Point:
def __init__(self, x=0,y=0):
self.x = x
self.y = y
def __str__(self):
return "x:{}, y:{}".format(self.x,self.y)
def __add__(self,other):
if isinstance(other,Point):
return Point(self.x + other.x, self.y + other.y)
return Point(self.x + other, self.y + other)
def __radd__(self,other):
... |
import collections
import numpy as np
import util
import svm
import csv
from ps2.ps2.ps2.src.spam.svm import train_and_predict_svm
def get_words(message):
"""Get the normalized list of words from a message string.
This function should split a message into words, normalize them, and return
... |
# 1부터 n까지 나머지 없이 딱 떨어지는 수를 더하면 되는데 반이 넘어가면 계산 안하고 걍 자기자신 더해주면 됨
def solution(num):
return num + sum([i for i in range(1, (num // 2)+1) if num % i == 0])
def test_solution():
assert solution(12) == 28
assert solution(5) == 6
|
# Python Program illustrating
# working of argmax()
import numpy as geek
# Working on 2D array
#array = geek.arange(12).reshape(3, 4)
array = geek.random.randint(0,100,(4,3))
print("INPUT ARRAY : \n", array)
# No axis mentioned, so works on entire array
print("\nMax element : ", geek.argmax(array))
... |
#!/usr/bin/python
print ("Hello gd34639\nPrzykład klasy pozycja w Pythonie class Pozycja\n")
class Pozycja:
"""Klasa przechowująca pozycję figury"""
x = 0
y = 0
def __init__(self, pole):
self.ustaw(pole)
def ustaw(self, pole):
self.x = ord(pole[0]) - ord('A') + 1
self.y = int(po... |
import numpy as np
import math
from pytope.polytope import Polytope
from scipy.optimize import linprog
class SupportFcn():
''' Support Function Class
Support Functions are a method of describing convex sets. They are defined
by
S(P; l) = sup {l^{T} x | x \in P }
for some convex set P. Th... |
import datetime
# Instructions:
# Practice: Companies and Employees
# Instructions
# Create an Employee type that contains information about employees of a company. Each employee must have a name, job title, and employment start date.
# Create a Company type that employees can work for. A company should have a busin... |
#!/usr/bin/env python
"""
exemplify grayscale color histogram
Parameters
Usage
Example
$ python <scriptname>.py --image ../img/<filename>.png
## Explain
"""
import matplotlib.pyplot as plt
import argparse
import cv2
def main():
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=T... |
#!/usr/bin/env python
"""
Exemplify thresholding, binarization of an grayscale image to either 0 or 255
--> select pixel value $p$ as threshold
Applications:
- preprocessing, focus on objects or areas of particular interest in an image
- segment foreground and background
Parameters
Usage
Example
$ pytho... |
#Nested_Lists
d = {}
for _ in range(int(input())):
s = input()
n = float(input())
d[s] = n
v = d.values()
l = sorted(list(set(v)))[1]
k = []
for key,value in d.items():
if value == l:
k.append(key)
k.sort()
for i in k:
print(i) |
#Chef_and_the_Wildcard_Matching
for _ in range(int(input())):
s=input()
t=input()
c=1
for i in range(len(s)):
if(s[i]==t[i]):
continue
elif(s[i]=='?'):
continue
elif(t[i]=='?'):
continue
else:
c=0
... |
#boy_or_girl
s=input()
a=set(s)
if(len(a)%2!=0):
print("IGNORE HIM!")
else:
print("CHAT WITH HER!")
|
#Zoos
s = input()
o = s.count('o')
z = s.count('z')
if o % 2 == 0 and o >= 2 * z:
print("Yes")
else:
print("No") |
#Lift_queries
la = 0
lb = 7
for _ in range(int(input())):
n = int(input())
if n - la <= lb - n:
print("A")
la = n
else:
print("B")
lb = n |
#Anagrams
from collections import Counter
for _ in range(int(input())):
a = input()
b = input()
A = Counter(a)
B = Counter(b)
e = A & B
d = e.values()
g = sum(d)
print(len(a)+len(b)-2*(g))
|
#Author - Roshan ghimire
#Amusing_Joke
from collections import Counter
s=input() #SANTACLAUS
t=input() #DEDMOROZ
m=input()#SANTAMOROZDEDCLAUS
if(Counter(s)+Counter(t)==Counter(m)):
print("YES")
else:
print("NO")
|
#HOW_MANY_DIGITS_DO_I_HAVE
n=input()
if(len(n)<=3):
print(len(n))
else:
print("More than 3 digits") |
#word_capitalization
s=input()
print(s[0].upper()+s[1:len(s)+1]) |
#Chef_and_Interactive_Contests
n , r = map(int,input().split())
for i in range(n):
a = int(input())
if a >= r:
print("Good boi")
else:
print("Bad boi")
|
#Teddy_and_Tweety
n = int(input())
a = n // 3
if a + a + a == n:
print("YES")
else:
print("NO") |
def islower(letter):
return letter.islower()
def generate(maxLen, word = "S"):
if len("".join(filter(islower, word))) > maxLen:
return
if word == "":
solution.add("#")
elif word.islower() and len(word) <= maxLen:
solution.add(word)
else:
for (index, letter) in enumer... |
# import time
# import os
# import pandas
# while True:
# if os.path.exists("files/temps_today.csv"):
# data = pandas.read_csv("files/temps_today.csv")
# print(data.mean()["st1"])
# else:
# print("File does not exist.")
# #time.sleep(10)
import json
import difflib
from difflib imp... |
word = input()
index =0
list=[]
flagAB=False
flagBA=False
while index<len(word)-1:
if word[index].lower()+word[index+1].lower() =="ab":
flagAB=True
index+=2
elif word[index].lower()+word[index+1].lower()=="ba":
flagBA=True
index+=2
else:
index+=1
if flagAB and flagBA:
... |
value = 0
age = 0
while value != -1:
value = int( input())
if value>=10 and value<=90:
if value >= age:
age = value
print(age)
|
x=int(input())
if x>0 and x<6:
print('khordsal')
elif x>=6 and x<10:
print('koodak')
elif x>=10 and x<14:
print('nojavan')
elif x>=14 and x<24:
print('javan')
elif x>=24 and x<40:
print('bozorgsal')
elif x>=40:
print('miansal')
|
def find_recurring_char(inp_string):
hash_table = {}
for x in inp_string:
if x in hash_table:
return(x)
else:
hash_table[x] = 1
return("Nothing Found!")
print(find_recurring_char("abca"))
|
# import packages
from qiskit import *
import numpy as np
import random as rand
def qAlice_output(strategy, inp):
if(strategy == 1):
return 0
elif(strategy == 2):
return rand.uniform(0,2*np.pi)
elif(strategy == 3):
if(inp == 0):
return 0
... |
import numpy
import math
import random
import collections
import matplotlib.pylab as plt
from collections import defaultdict
def dot(v, w):
return sum(v_i * w_i for v_i, w_i in zip(v,w))
def sum_of_squares(v):
return dot(v,v)
def mean(x):
return sum(x) / len(x)
def de_mean(x):
x_bar... |
class Link:
"""A linked list.
>>> s = Link(1)
>>> s.first
1
>>> s.rest is Link.empty
True
>>> s = Link(2, Link(3, Link(4)))
>>> s.first = 5
>>> s.rest.first = 6
>>> s.rest.rest = Link.empty
>>> s # Displays the contents of repr(s)
Link(... |
# Constructor
def tree(label, branches=[]):
for branch in branches:
assert is_tree(branch)
return [label] + list(branches)
# Selectors
def label(tree):
return tree[0]
def branches(tree):
return tree[1:]
def is_tree(tree):
if type(tree) != list or len(tree) < 1:
return False
... |
#Add a legend title and axis labels to this plot to plot from lab 8.8.py
import numpy as np
import matplotlib.pyplot as plt
minSalary = 20000
maxSalary = 80000
minAges = 21
maxAges = 65
numberOfEntries = 100
# this is so that the "random" numbers are the same each time to make it easier to debug.
np.random.seed(1)
... |
#This program taken in a float from the user and outputs the absolute value of that float
# Author: Ciaran Moran
number = float(input("Enter a number:"))
absoluteValue = abs(number)
print('The absolute value of {} is {}'.format(number, absoluteValue)) |
# nameAndAge.py
# This program reads in Users name and age, then prints it out
# Author: Ciaran Moran
name = input("What is your name?:")
age = input("What is your age?:")
print('Hello {},\t your age is {}.'.format(name,age))
|
# es.py
# This program reads in a text file from an arguement on the command line.
# It outputs the number of "e" characters in the file.
# Author: Ciaran Moran
import os
import sys
filename = sys.argv[1] # accept the 2nd arguement from the command line
def readFile(filename):
with o... |
#This program takes a user input as a float as this datatype will accept decimal places (9.44 dollars mentioned in question)
#Next converts the float to an abso1ute value (to remove and negative signs)
#Next converts the absolute value to cent and rounds result to the nearest integer (zero decimal places)
#Author: Cia... |
str="space remove"
ans=""
cnt=0;
for i in str:
if i==' ':
cnt+=1;
continue;
ans=ans+i;
for i in range(0,cnt):
ans='_'+ans;
print("\n");
print("after moving space to front (_ represented as space) ",ans);
print("\n"); |
import copy
class Input:
data = None
concrete = False
def __init__(self):
pass
def __len__(self):
return len(self.data)
def copy(self):
#print "data:",self.data
return copy.copy(self)
def isSymbolic(self):
return not self.concrete
def isConcrete(self):
return self.concrete
... |
import os
import getpass
import random
print(" ------------------------\n| Piggy's Trolling Tools: |\n| :-: Folder Creator :-: |\n ------------------------\n")
where = input("Input directory where folders should be created: ")
name = input("Enter folder name: ")
total = int(input("Enter amount of Folde... |
"""
Simple graph implementation compatible with BokehGraph class.
"""
import random
class Vertex:
def __init__(self, vertex_id, x=None, y=None):
self.id = vertex_id
self.edges = set()
if x is None:
self.x = random.random() * 10 - 5
else:
self.x = x
i... |
import socket
import sys
import zipfile
import os
host = '127.0.0.1'
port = 1337
k = int(sys.argv[1])
zip_name = 'main.zip'
s = socket.socket()
print('[+] Client socket is created.')
s.connect((host, port))
print('[+] Socket is connected to {}'.format(host))
with zipfile.ZipFile(zip_name, 'w') as file:
for j in ra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.