text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 15:10:56 2019
@author: jinyanliu
"""
class intDict(object):
"""A dictionary with integer keys"""
def __init__(self, numBuckets):
"""Create an empty dictionary"""
self.buckets = []
self.numBuckets = numBuckets... |
x,y=raw_input('Enter balance ane interest rate:').split()
balance=float(x)
rate=float(y)
lixi=balance*(rate/1200)
print('The interest is '+str(lixi))
|
def eliminateDuplicates(lst):
s=[]
for i in lst:
if i not in s:
s.append(i)
print(s)
if __name__ == '__main__':
a=raw_input('Enter ten number:')
l=a.split()
eliminateDuplicates(l)
|
import math
def distance(x1,y1,x2,y2):
return math.sqrt((x2-x1)**2+(y2-y1)**2)
x,y,n,m=eval(raw_input('>>'))
print(distance(x,y,n,m))
|
import math
x,y=raw_input('Enter the radius and length of a cylinder:').split()
radius=float(x)
length=float(y)
area=radius*radius*math.pi
volume=area*length
print('The area is '+str(area)+'\n'+'The volume is '+str(volume))
|
import random
def shuffle(lst):
l= len(lst)
s=[]
for i in range(l):
n=random.randint(0,len(lst)-1)
s.append(lst[n])
lst.pop(n)
print(s)
if __name__ == '__main__':
a=raw_input('>>')
b=a.split()
print(b)
shuffle(b)
|
def indexOfSmallestElement(lst):
m=min(l)
print(m)
for i in range(len(l)):
if l[i]==m:
print(str(i)+' ',end="")
print()
if __name__ == '__main__':
a=input('>>')
l=a.split()
indexOfSmallestElement(l)
|
# -- coding: utf-8 --
#1
print("-[Задание 1]-")
print("Введите число 1: ")
a = int(input())
print("Введите число 2: ")
b = int(input())
print("Введите число 3: ")
c = int(input())
print("Сумма введённых чисел: ",a+b+c)
#2
print("-[Задание 2]-")
print("Введите катет А: ")
a = int(input())
print("Введите катет Б: ")... |
import sys
cols = """name,age,gender,raceethnicity,month,day,year,streetaddress,city,state,latitude,longitude,state_fp,county_fp,tract_ce,geo_id,county_id,namelsad,lawenforcementagency,cause,armed,pop,share_white,share_black,share_hispanic,p_income,h_income,county_i""".split(",")
def max():
for line in sys.stdin:
... |
import sqlite3
from db import *
ranks = ['Новичок ☕', 'Любитель ①', 'Опытный Кликер ②', 'Профессиональный Кликер③', 'Мастер ⋆', 'Гранд-Мастер ⋆⋆⋆', 'Величайший Кликер ㉨㉨㉨', 'Элита ╰☆╮']
def get_price(id):
sql = f"SELECT * FROM users WHERE uid={id}"
cursor.execute(sql)
info = cursor.fetchone()
... |
# Convert a flat sequence of numbered list labels such as
# 1 2 a b 3 4
# into a hierarchical structure like
# 1, 2, [a, b] 3, 4
#
# Works on the sorts of symbols found in the DC Code, which
# get quite interesting like QQ-i (which is between PP and
# either QQ-ii or RR).
#
# Try:
# 1 2 2A 2B A B 3 A B C D E F G ... |
# NO IMPORTS!
##############
# Problem 01 #
##############
def find_triple(ilist):
""" If the list ilist contains three values x, y, and z such that x + y = z
return a tuple with x and y. Otherwise return None. """
s = set(ilist)
for i in range(len(ilist)):
for j in range(i+1,len(ilist)):
... |
# coding: utf-8
# # Tent Packing
# In[ ]:
from instrument import instrument
# In[ ]:
# Pack a tent with different sleeping bag shapes leaving no empty squares
#
# INPUTS:
# tent_size = (rows, cols) for tent grid
# missing_squares = set of (r, c) tuples giving location of rocks
# bag_list = list of sets, ea... |
''' Write a Python program to get a string from a given string where all occurrences of its first char
have been changed to '$', except the first char itself ?'''
import time
n=str(input("Please enter the string :"))
print("Changing all the occurrences of first char of the string to $ ...")
time.sleep(1)
str_1=n... |
# Write a Python function that takes a list of words and returns the length of the longest one?
import time
list_1=[]
max_list=[]
i=0
n=int(input("Please enter the n of elements you want to put in the list :"))
while i<n:
ele_list=input("Please enter the elemnt :")
list_1.append(ele_list)
i+=1
print("Prepa... |
# Unittest for simple calculator
# author: Muztrizen
import unittest
import calculator
class TestCalculator(unittest.TestCase):
def test_add(self):
"""
Test case: Normal case of addition
"""
expected_answer = 1
actual_answer = calculator.add(1, 0)
self.assertEqual(expected_a... |
class BST:
class Node:
def __init__(self, key, data, parent = None):
self.quantity = 1
self.key = key
self.data = data
self.parent = parent
self.left = None
self.right = None
def __init__(self, lambda_key):
self.lambda... |
"""
Controller is the one class to rule them all! It's responsible for the communication of model and view
"""
from Conect4_View import View
from Conect4_Model import Model
from itertools import product
class Controller:
""" Creates logic for communication model and view. """
def __init__(self):
""" ... |
"""
Monte Carlo Tic-Tac-Toe Player
"""
import random
import poc_ttt_gui
import poc_ttt_provided as provided
# Constants for Monte Carlo simulator
# Change as desired
NTRIALS = 100 # Number of trials to run
MCMATCH = 1.0 # Score for squares played by the machine player
MCOTHER = 1.0 # Score for squares played by ... |
# Generator for the prime number sequence
def prime(n):
counter = 1
primes = []
candidate = 2
while counter <= n:
hasDivisor = False
for prime in primes:
hasDivisor = (candidate % prime == 0)
if hasDivisor or prime > candidate**(.5):
break
... |
# Define a generator of the fibonacci sequence; want to evaluate this in lazy and space efficient fashion
def fib(n):
last = 0
penult = 0
current = 0
counter = 1
while counter <= n:
if counter > 1:
penult = last
last = current
current = last + penult
... |
def word_count(filename):
file = open(filename)
word_list = []
for line in file:
line = line.rstrip()
words = line.split(" ")
word_list.extend(words)
words_in_file = {}
for word in word_list:
words_in_file[word] = words_in_file.get(word, 0) + 1
for word, ... |
import turtle
from Pong_Build_Game import *
# Functions
def paddle_a_up():
y = paddle_a.ycor()
y += 20
paddle_a.sety(y)
def paddle_a_down():
y = paddle_a.ycor()
y -= 20
paddle_a.sety(y)
def paddle_b_up():
y = paddle_b.ycor()
y += 20
paddle_b.sety(y)
def paddl... |
class A:
def __init__(self):
self.var1=4
print (self.var1)
def add(self,x,y):
print (self.var1)
return x+y
class B(A):
def __init__(self):
self.var1 = 5
print (self.var1)
a = A()
b = B()
b.add(3,3)
|
class Printer:
def __init__(self, extruders, price, has_misp):
self.extruders = extruders
self.price = price
self.has_misp = has_misp
@property
def extruders(self):
print("Get extruders")
return self._extruders
@extruders.setter
def extruders(self, value):
if not isinstance(value, int):
raise Type... |
#econtactbook.py
#
#Tyler Clark
#23 Dec 2012
#
#a text based contact book that can store, update, and retrieve a
#contact's name, address, phone number, and email by using an xml file
#
#
import xml.etree.ElementTree as ET
#xml parser
class Tree:
#returns root of existing ebook xml file or creates new one
... |
import numpy as np
print("Hallo Welt")
'''
W = np.array([[1.,2,3], [3,4,5]])
print(W.shape)
print(W.shape[0])
print(W.shape[1])
print(W.T.shape)
'''
M=np.arange(12).reshape(3,4)
print("Basic Array")
print(M)
print("*"*40)
print(M[:1])
'''
print(M[1,:])
print(M[1])
print(M[:,1])
print(M[:,[1]])
print(M[:,[3,0,1,1]... |
import random
randNum = random.randint(1,50)
print("Welcome to Guess the number game !!")
print(randNum)
userNum = int(input("Enter your number"))
while True:
if (randNum == userNum):
print("Congratulation you won !!")
break
elif (randNum > userNum):
print("Opps ...Your number is less..... |
class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
sums = 0
self.dp = []
self.nums = nums
for index, num in enumerate(nums):
self.dp.insert(index, sums + num)
sums += num
def sumRange(self, i, j):
... |
# Definition for a binary tree node.
from functools import reduce
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
... |
from CityInformation import CityInformation
from flask import Flask, request
app = Flask(__name__)
c = CityInformation()
@app.route('/')
def home_page():
return """
<form action="/closest-neighbors" method="post">
Use this form to search for closest neighbors to a certain geo_id: <br>
Enter the geo_id:... |
# Santiago Naranjo
# 10 de agosto de 2020 primer entrega
# 24 de agosto de 2020 segunda entrega
# Mejoradas funciones de suma,resta, multiplicacion y division, agragadas funciones con matrices
import math
#crea una lista de 4 elementos donde los primeros 2 son un numero complejo y los otros 2 otro
#recibe dos l... |
"""
validator.py
Steve Ashman
Basic validation library for console apps
"""
def get_valid_selection(valid_options, display_options):
"""
Gets a valid selection from stdin matching one of the provided options
:param valid_options: list of valid options for selection
:param display_options: function for... |
for i in range(1, 100):
if i % 2 == 0 and i >= 20:
print("Not Weird", i, "this is from first condition")
elif i % 2 == 0 and 6 <= i <= 20:
print("Weird", i, "this is from second condition")
elif i % 2 == 0 and 2 <= i < 5:
print("Not Weird", i, "this is from last condition")
else:... |
#TODO Class Variables
"""
Reference: Class Objects
The way these objects work are whenever the instance variables are initialized
if the instance variables themselves don't have an attribute they go looking for
that variable in the class to which they belong and inherit the value from there
this will print the values... |
def median(size, values):
if size % 2 == 0:
median = (values[int(size / 2) - 1] + values[int(size / 2)]) / 2
else:
median = values[int(size / 2)]
return int(median)
size = int(input())
numbers = sorted(list(map(int, input().split())))
if size % 2 == 0:
data_low = numbers[0... |
# Hordó bor, befér nem fér
# Van egy henger alakú hordónk,
# melybe nem tudjuk, hogy belefér-e a rendelkezésre álló bor.
# Kérd be a bor mennyiségét literben, majd a hordó
# összes szükséges adatát cmben. Adj tájékoztatást,
# hogy hány literes a hordó, és hogy belefér-e a hordóba a bor!
# Ha belefér, akkor add me... |
class attendanceshortageexception(Exception):
def __init__(self, arg):
self.msg=arg
class incomeexception(Exception):
def __init__(self, arg):
self.msg=arg
class gpaexception(Exception):
def __init__(self, arg):
self.msg=arg
gpa = int(input("Enter cgpa:"))
if gpa<7:
raise gpa... |
i=0
m=0
dict={12345:"Siddhant",
12346:"Samer",
12347:"Suyog",
12348:"Saurabh",
"Statement":[]}
while(i==m):
Ac_number=int(input("Enter your Account Number"))
x=dict.get(Ac_number)
if Ac_number in dict :
print("Your Name is",x)
Amount=int(input("Please enter opening balance... |
"""A module for sets of tiles that make up a component of a map, such as a room or corridor"""
import random
import mapfeatures
class MapComponent():
def __init__(self, world_coordinates, width, height):
self.w_x, self.w_y = world_coordinates
self.width = width
self.height = height
... |
class union_find:
# Getters
def get_num_components(self):
return self.num_components
def print_parents(self):
for i in range(self.n):
print("%d -> %d\n" % (i, self.parent[i]))
# Constructor
def __init__(self, n):
# initialize your arrays here
... |
def fizz_buzz(i):
if i%15 == 0: #Test for FizzBuzz
return("FizzBuzz")
elif i%3 == 0: #Test for Fizz
return("Fizz")
elif i%5 == 0: #Test for Buzz
return("Buzz")
else: #Condition if not Fizz,Buzz or FizzBuzz
return (i) |
def Main():
print("LEARNING PYTHON - ITERATION (looping words)")
words = ['cat','bat','hat','rat','sat']
for word in words:
print(word)
if __name__ == "__main__":
Main() |
firstName="Mohammad"
midName="Febri"
lastName="Ramadlan"
fullname=firstName+" "+midName+" "+lastName
print(fullname)
print(firstName)
print(fullname[3])
print(fullname[0:10])
print(fullname[3:]) |
import random
from copy import deepcopy
class Matrix:
def __init__(self, nrows, ncols):
self.nrows=nrows
self.ncols=ncols
self.matrix=[]
for i in range(self.nrows):
row=[]
for j in range(self.ncols):
row.append(random.randint(0,9))
... |
print "enter the limit"
n=int(raw_input())
i=1
s=0
while i<=n:
s=s+i
i=i+1
print "sum is",s
|
"""@Author: Maria DaRocha
Date: 23-8-2020
Title: Python Tutoring Session One
@Topics: Python 3 Basics
Arithmatic Operators
Boolean Operators
Importing
Lists
Print
Strings
Type Checking
@Source: https://www.learnpython.org
"""
#Demo a simple func... |
name = input ("What is your name? ")
age = input ("How old are you? ")
numberofyearsto100 = 100 -int(age)
yearof100age = 2018 + numberofyearsto100
print("Your name is " + name " and will be 100s old in" + str(yearOf100Age))
|
#!/usr/bin/python
"""
email_terminal.py is a script written by Tina Quach (quachtina96@gmail.com). It
is meant to be game that reflects the email experiences of the typical MIT
undergraduate living in East Campus. Given that the script prompts for your email
information, and pulls real emails out of your inbox for ... |
numV = 4
a = [[True,True,False,False],[False,False,False,True],[True,False,True,False],[False,True,False,True]]
def Warshall(A,numV,W):
for i in range(numV):
for j in range(numV):
W[i][j] = A[i][j]
i=0
j=0
for k in range(numV):
for i in range(numV):
for j in ran... |
# Write your solution for 1.2 here!
x=0
for i in range(101):
if i% 2==1:
x+=i
print(x) |
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not u... |
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
Given a m x n grid filled with non-negative numbers,
find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
"""
class Solution(object):
def minPathSumRecu... |
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
... |
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
Given a 2D binary matrix filled with 0's and 1's,
find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.
"""
class Solution(object):
def maximalRectangle(self... |
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1).
You begin the journey with an empty tank at one of... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 27 16:45:19 2014
@author: john
"""
#Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
#Convert Sorted Array to Binary Search Tree
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
se... |
class Solution:
# @param s, a string
# @return a string
def reverseWords(self, s):
words = s.split(None,-1)
print len(words)
print words
result=""
wordsLen = len(words)
if wordsLen < 2:
return ""
for i in range(wordsLen-1,-1,-1):
... |
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Try to solve it in linear time/space.
Return 0 if the array contains less than 2 elements.
You may assume all elements in the array are non-negative integers and f... |
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
Given a binary tree, return the zigzag level order traversal of its nodes' values.
(ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
ret... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 01 14:15:57 2014
@author: john
"""
#Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSameTree(self,p, q):
if p==None and q==None:
... |
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
Given an unsorted array of integers, find the length of longest continuous increasing subsequence.
Example 1:
Input: [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3.
Even though [1,3,5,7] is also an increasing... |
import itertools
class Solution(object):
def triangleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
iters = itertools.combinations(nums, 3)
result = 0
for it in iters:
if self.isValidTriangle(it):
result += 1
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 01 14:34:54 2014
@author: john
"""
class Solution:
# @param A a list of integers
# @return nothing, sort in place
def swap(self,A,a,b):
tmp=A[a]
A[a]=A[b]
A[b]=tmp
def sortColors(self, A):
if A==Non... |
# -*- coding: utf-8 -*-
__author__ = 'yghou'
"""
Write an efficient algorithm that searches for a value in an m x n matrix.
This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Co... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
X=pd.read_csv('./Linear_X_Train.csv')
Y=pd.read_csv('./Linear_Y_Train.csv')
#convert pandas into numpy
X=X.values
Y=Y.values
#Normalization
u=X.mean()
std=X.std()
X=(X-u)/std
#visualize
pl... |
class DNode:
def __init__(self, item=None):
self.item = item
self.right = None
self.left = None
class DoubleLinkedList():
def __init__(self):
self.root = None
def append(self, item):
NewNode = DNode(item)
CurNode = self.root
if self.ro... |
tar, s1, s2 = input().split()
s1s = set(input().split())
s2s = set(input().split())
if tar in s1s and tar in s2s:
print("MrMaxValu")
elif tar in s1s:
print("MrMax")
elif tar in s2s:
print("MaxValu")
else:
print(-1)
|
# age = input("How old are you?\n") #blocked 1-5, Ctrl/
# if int(age) >= 21:
# print("You are old enough.")
# else:
# print("you are not old enough.")
age = int(input("How old are you?\n"))
if age == 21:
print("You are a great age to party.")
elif age > 37:
print("Your getting up there in age!")
elif ... |
name = input("What is your name?")
num = len(name)
## You can have multiple conditions here
if num > 3 and num < 15: # Both statements must be truthy
if num == 4:
print('Perfect length!')
else:
print("It's an okay length.")
print(f"Welcome {name}.")
else:
print('%s is not a good number o... |
#nesting putting one thing inside another
name = input("What is your name?")
if len(name) > 3: #counting the length of the value
print("Your name is long enough.")
if len(name) > 15:
print("That is way too long.")
else:
print(f"Welcome {name}")
name = input("What is your name?")
if len(n... |
# Nesting Code Block
## Objective
- Put code blocks inside of code blocks
- Use multiple condition
- Exercise
## Terms
- *Nesting* - `In programming nesting describes putting code blocks or other syntaxtual items inside of another item`
## Put code blocks inside code blocks
- ```python
name = input("what is your na... |
# 201016 Class Reading "Sequences: Lists, Strings, and Tuples"
# Small Exercises
# 1. Sum the Numbers
# Create a list of numbers, print their sum.
##declare list
nums = [1, 2, 3, 4]
##print sum
print(sum(nums)) |
# Lists
## Objectives
- What are the parts of a list?
- Creating lists
- Accessing items from a list
- Exercises
## Terms
- *lists* - `Lists are a data type of ordered gropuing of values. They are called arrays in most other languages.`
- *index* - `In a list or an array, it is the number representation of the posi... |
# 1. import GUI library
from tkinter import *
# 2. create an object of type tkinter
window = Tk()
# 3. set: title, size(geometry), background-color
window.title('Graphical User Interface')
window.geometry('450x350')
window.configure(background='pink')
# 4. create label & entry
lbl1 = Label(window, text="Username",
... |
##获取日期
# import datetime
# nowday=datetime.date.today()
# nday=(datetime.date.today() + datetime.timedelta(days = -3)).strftime("%Y-%m-%d")
# print("今天日期:",nowday)
# print("n天前日期:",nday)
#pandas读取csv文件
import pandas as pd
df = pd.read_csv("D:\\2021-12-31demo_assignDayData.csv")
print(df.to_string()) |
#output row of Pascal's triangle given row number, starting at 1
#use a list of lists to represent the triangle
#get n
rownum = int(input("Enter row number of Pascal's triangle: "))
if rownum <= 0:
print("Must have positive nonzero input. Start again")
else:
#put first two rows into triangle
triangle = [[1... |
# #Get number of Prime Factors for a number input by user
import math
def is_prime(n):
#to determine if a number is prime or not
if(n==1):
return False
elif(n==2):
return True
else:
for x in range (2,n):
if(n % x == 0):
return False
return True
#... |
# Linear regression
# packagaes
import numpy as np
import pandas as pd
# y_i = beta0 + beta1 x1_i + beta2 x2_i + epsilon
# data generating proces - inserted from exam description
def DGP(N):
# a. independent variables
x1 = np.random.normal(0,1,size=N)
x2 = np.random.normal(0,1,size=N)
# b... |
from lib import *
import time
def is_divisible(num):
return all((num[i + 1] * 100 + num[i + 2] * 10 + num[i + 3]) % p == 0 for (i, p) in enumerate([2, 3, 5, 7, 11, 13, 17]))
def run():
return sum(int(''.join(map(str, num))) for num in permutations(list(range(10))) if is_divisible(num))
clear()
print('Challenge #4... |
from time import time
# Здесь необходимо реализовать
# контекстный менеджер timer
# Он не принимает аргументов, после выполнения блока он должен вывести время выполнения в секундах
# Пример использования
# with timer():
# sleep(5.5)
#
# После завершения блока должно вывестись в консоль примерно 5.5
class timer:
... |
import os.path
PATH = os.path.dirname(os.path.abspath(__file__))
def solve(problem_set: set):
for number in problem_set:
diff = 2020 - number
for num in problem_set:
second_diff = diff - num
if second_diff in problem_set:
return (number * num * second_dif... |
import re
# Input string
value = "Tiny programs that process text."
match = re.search("(process.*)", value)
if match:
print("Search result:", match.group(1))
match = re.match("(pr.*)", value)
if match:
print("match:", match.group(1))
|
# Zaimplementuj funkcję, która na podstawie podanej listy stworzy nową listę zawierającą tylko elementy
# oryginalnej kolekcji z podanego zakresu.
# Funkcja powinna przyjmować trzy parametry:
# listę
# początek zakresu
# koniec zakresu
# Przykład użycia:
# >>> filtruj([-2, 10, 0, 5, 1, 16, 9], 5, 15)
# [10, 5, 9]
def ... |
# -*- coding: utf-8 -*-
"""
Investment Growth Graph
@author: MadMerlyn
"""
num_years = 30
from invest import Invest
import matplotlib.pyplot as plt
#Build data-table
_data = Invest(1000, 400, 0.08, years=num_years)
annual = range(12,(12*num_years)+1,12)
#Generate lists from data-table
plot_data = [item for ... |
def divide(a,b):
try:
print (a/b)
except ZeroDivisionError :
print (a/1)
except TypeError as err:
print(err)
print("pass only numbers")
except :
print("Error ")
divide(10,0)
#ZeroDivisionError:
#TypeError: |
class Student:
sId = input("sid : ")
sName = input("sName :")
sAddr = input("sAddr :")
sPhone = input("phone no. :")
def get_student_details(self):
print(" Student data")
print("==============")
print("Student ID :" , self.sId)
print("... |
# a=float(input("enter value: "))
# b=float(input("enter value: "))
# c=float(input("enter value: "))
# if a>b :
# if a>c :
# print("%d is biggest no."%a)
# else:
# print("%d is biggest no."%c)
# elif b>c:
# if b>a :
# print("%d is biggest no."%b)
# else :
# print("%d is... |
# str = "Durga Software Solutions"
# a = 0
# while a < len(str):
# print(str[a])
# a = a+ 1
# a=int(input("enter value :"))
# if a>1 :
# for x in range(2,a) :
# if a % x ==0 :
# print(a ,"not prime no")
# break
# else :
# print(a ,"is a prime no")
# fibon... |
import os
# file = open("c:/classss/ABC/hello.txt" , "w")
# print("File mode :" , file.mode)
# print("File Name :" , os.path.basename(file.name))
# print("File Directory :",os.path.dirname(file.name)) ## Get Parent location :
# print("Absolute Path :",file.name)
# print("Absolute ... |
# convert Python dictionary object (sort by key) to JSON data. Print the object members with indent level 4
import json
python_dict = {'English': 78, 'Maths': 88, 'Computers': 100}
print(json.dumps(python_dict, sort_keys = True, indent = 4)) |
import turtle as t
import random as r
def tree(direction,level):
temp=0
t.pensize(10-level)
if(level<=5):
t.pencolor((100+level*30,0,0))
temp=r.random()*10
elif(level<=9 and level>5):
t.pencolor((0,100+(level-6)*30,0))
if(direction==1):
t.left(20)
elif(direction=... |
# -*- coding: utf-8 -*-
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words): #manglet ‘:’
"""Prints the first word after popping it off.""... |
import unittest
import datetime
class TestCase (unittest.TestCase):
def test_date(self):
Date = "1992-04-08"
Today = str(datetime.datetime.now())
result = Today > Date
self.assertTrue(True,result)
self.assertFalse(Today < Date,result)
if __name__ == '__main__':
unitte... |
#!/usr/bin/env python3
#converts binary to hexadecimal
#maybelittleendianstyle
import sys
#print("Binary", list(binary))
class InvalidBinary(Exception):
pass
class BinaryToHex:
def binary_to_hex(self, binary):
#system check for binary digits only
for digit in list(binary):
if d... |
# -*- coding: utf-8 -*-
"""
Simple study related to threads performance
"""
import time
import random
import threading
parallel = random.choice(['True', 'False'])
counter = 0
max_for = 100000000
lock = threading.Lock()
def add_numbers():
global counter
for _ in range(0, max_for):
lock.acquire()... |
# -*- coding: utf-8 -*-
"""
Simple study related to Multiprocessing
"""
import os
from multiprocessing import Process
#function 1
def calculate_square(n):
print('calculated square:', n*n)
proc = os.getpid()
print('{0} process id:'.format(proc))
#function 2
def calculate_cube(n):
print('calculated c... |
import unittest
from hashing import *
class test_Hashtable(unittest.TestCase):
def test_Get_GeneralCase(self):
# Check the case where the element is present in the table; returns value
H = HashTable()
H[54]="Data Structures"
self.assertEqual(H.get(54), 'Data Str... |
"""
..module: Assistant - help to guess the riddled number by suggesting the list of the optimal requests
..author: Sergey Sumburov <sumburovsn@gmail.com>
"""
import random
# game_log dictionary keeps all the responses of the current session of the game
# in form "attempt: response"
game_log = {
'1234':... |
# OPTION 1
# def fib(n, output=None):
# if n < 2:
# return 0
# if output is None:
# a = 0
# b = 1
# output = [a, b]
# if len(output) <= n:
# c = output[-1] + output[-2]
# output.append(c)
# fib(n, output)
# return output
# OPTION 2 : running iter... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.