text stringlengths 37 1.41M |
|---|
# A heap is a complete binary tree
# A complete binary tree's leaf level is all left skewed with no gaps in between and all nodes in previous level should have two children always
# Heap is also a priority queue
# it's queue except every nodes has a priority and the node with the highest priority is the one th... |
# Remove and replace
# Prompt:
# 1) Replace each "a" by two "d"s
# 2) Delete each entry containing a "b"
# Input:
# -> an array of characters
# -> an integer that denotes the number of entries of the array that the operation
# is to be applied to
# Note: One can assume there is enough space in the array to hold ... |
#!/usr/bin/python
#Solution for printing groups of similar words
import re
import collections
import Trie
import makegroups
import fileutils
#getting dictionary containing word vs list of words similar to key
#internally used trie
similarWords = fileutils.getSimilarWordDictionary()
groupingUtils = makegroups.Group... |
print(" *** WELCOME TO KM->MI OR MI->KM CONVERTOR *** ")
method=0
km=0
mi=0
ratio= 0.621371 #1Km = 0.621371 miles
while (method!=1 and method !=2):
print("Enter 1 to convert Kilometers to Miles")
print("Enter 2 to convert Miles to Kilometers")
try:
method = int(input("Your choice : "))
except:... |
print(" *** WELCOME TO LEAP YEAR PROGRAM *** ")
year=0
leap=False
while year<500:
try:
year = int(input("Enter the year : "))
except:
print("Please enter a valid year! ")
if (year%4)==0:
if (year%100)==0:
if (year%400)==0:
leap=True
else:
leap=True
... |
# the function anagram will identify if words contain the same letter
def anagram(word, word_list):
# the variable sorted_word holds the function sorted() which sorts the word whose anagrams we need
sorted_word = sorted(word)
# ana_gram is a container that holds words with identical letters
ana_gram = []
# 'wo... |
#!/usr/bin/env pythonw
import argparse
import json
import monte2
import matplotlib.pyplot as plt
# These should be private. Will cover later
# For numeric parameters, these are lower and upper bounds if there are bounds.
# For strings, these are constraints on values if there are any.
trading_days_lbound = 10
trading_... |
import BInaryTree
import queue
class PaperFolding:
def __init__(self, N):
self.N = N
self.tree = BInaryTree.BinaryTree()
def main(self):
#创造二叉树
self.folding_process()
#遍历二叉树
self.midErgodic()
print(self.ls)
def folding_process(self):
... |
#!/usr/bin/python3
#One Dimensional Cellular Automata
#Author: Cristhian Eduardo Fuertes Daza
#Class managing logic and computation of lattice's cells
class CellularAutomata():
#Constructor
#params:
#numCells: the number of cells in each generation
#rule_name: string representing the name of the rule t... |
# Document at least 3 use cases of static methods
"""
Static methods do not take the 'self' or 'cls' parameters although they can take any number of arguments.
They cannot modify object or class state except when called by class or instance methods. In this wise,
they can be called helper functions which is one way t... |
class Quick_sort():
def __init__(self, array):
self.quick_sort(array)
def quick_sort(self, array):
tamanho = len(array)
self.quick_recursivo(array,0,tamanho-1)
def quick_recursivo(self, array,primeiro_elemento,ultimo_elemento):
if primeiro_elemento<ultimo_elemento:
... |
# TODO: Add arithmetic operations
# TODO: Add string/print operations
class PositionBase(object):
def __init__(self, x=0, y=0):
self._x = x
self._y = y
def x(self):
return self._x
def y(self):
return self._y
class Position(PositionBase):
def __init__(self, x=0, y=0,... |
def maximum_path_sumI(triangle):
if len(triangle) == 1:
return triangle[0][0]
else:
max_item = max_items(triangle[-1]) # => 1 # return max num between every two number in the last arr in triangle
added_item = add_items(max_item, triangle[-2]) # => 2 # add all items in... |
from datetime import date
def counting_sundays(first_year, last_year):
sundays = 0
for year in range(first_year, last_year+1):
for month in range(1, 13):
if date(year, month, day=1).weekday() == 6:
sundays += 1
return sundays
|
# this is not the efficient solution for large numbers
def prime_summation(num):
list_of_primes = []
for i in range(2, num):
if is_prime(i):
list_of_primes.append(i)
return sum(list_of_primes)
def is_prime(num):
prime = True
for i in range(2, int(num/2)+1):
if ... |
#creating a tuple
tup=("mango",66,58.0,"hello world")
# print(tup)
#accessing a tuple
# print(tup[1:])
# print(tup[::-3])
# print(tup[1:2])
# print(tup[0:3])
# print(tup[::-1])
#updation of a tuple ### tuple updation is not possible throws an error coz tuple is immutable
# tup[0]="good morning"
#adding a ... |
# #aceesing a string
# dt="hacker"
# b="software"
# print(dt[0:])
# print(dt[::-1])
# print(dt[:-2])
#concatinating
# data=dt[0:]+"software"
# print(data)
# data=dt+b
# print(data)
# data=dt+"micro"
# print(data)
#replication
# data=dt*5
# print(data)
#slicing
# print(dt[0:4])
# print(dt[-6:-1])
# me... |
#reverse of a string
# str=input("enter a string to reverse:")
# a=len(str)
# for i in reversed(str):
# print(i)
#slicing a string
# s=input("enter a string:")
# print(s[2:5])
#finding the maxium length of a string
# s1,s2=input("string 1:"),input("string2:")
# a,b=len(s1),len(s2)
# if (a>b)&(a!=b):
# ... |
#is operator
# a=[2,5,1,2,9,9,6,3]
# y=[9]
# y==9
# print(y is a)
# not is
a=[5,8]
b=[5,8]
print(a is not b) |
# this project is done in collaboration with Jorge Henriquez (https://github.com/penguingovernor)
# this program takes an image and pixelates it!
from PIL import Image
import argparse
import sys
# Get the photo from the command line
parser = argparse.ArgumentParser(description="turns a photo into a ppm file")
parser... |
# Creating Files in Python:
# first make a file with txt toward make a text file
# Read a text file by open commands.
# syntax
#r = open('file location','mode')
r = open('c:\myfile.txt', 'r') # r mode is for reading
print(r.read())
# to reprint from start
r.seek(0) # type '0' ZERO whic... |
from langdetect import detect
from langdetect import DetectorFactory
import sys
def getLang(text, set_lang):
try:
DetectorFactory.seed = 0
lang = detect(text)
if lang in ["hi"]:
return lang
elif lang in ["ko", "zh-tw", "zh-cn"]:
retur... |
#!/usr/bin/env python3
nums = set()
a = 2
while a <= 100:
b = 2
while b <= 100:
nums.add(a**b)
b += 1
a += 1
print(len(nums))
|
#!/usr/bin/env python3
def prime_factors(n):
factors = []
lastresult = n
c = 2
while lastresult != 1:
if lastresult % c == 0 and c % 2 > 0:
factors.append(c)
lastresult /= c
c = c + 1
else:
c = c + 1
return factors
# print prime_facto... |
# Uses python3
import sys
def fibonacci_partial_sum_naive(m, n):
f=[]
m = m % 60
n = n % 60
if n < m:
n = n + m + 1
sum = 0
if n == 1:
return 1
for i in range(n):
if i == 0 or i == 1:
f.append(1)
else:
f.append( (f[i-1] + f[i-2]) % ... |
# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
print("Hello world")
"""
Write a NumPy program to find the number of elements
of an array, length of one array element in bytes and total
bytes consumed by the elements.
"""
import numpy as np
array = ... |
"""
Name : AbdElrahman Ibrahim Zaki
Email : abdelrahmanzaki.aez@gmail.com
Project : C - Number Guess Game - main file
"""
from function import play
winning_trial = 0
losing_trial = 0
trials = 0
print(" --------- Welcome to Number Guess Game! --------- \n")
winning_trial, losing_trial... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
fin = open('words.txt')
def uses_all(words, letters):
for letter in words:
if letter not in letters:
return False
return True
if __name__ == "__main__":
print uses_all('abcdefg', 'acd') |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
def is_power(a,b):
#this function is a power of b
if b == 0:
print 'anynumber is not divisable by 0'
return None
elif a == b:
return True
elif a % b == 0:
return is_power(a/b,b)
else:
return False
def is_power_cu... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
def letter_backward(str):
#this function takes a string as an argument and displays the letters backward, one per line.
if len(str) == 0:
print 'Over'
else:
for i in range(len(str)):
print str[-i-1]
if __name__ == "__main__":
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
def invert_dict(d):
"""Inverts a dictionary, returning a map from val to a list of keys.
If the mapping key->val appears in d, then in the new dictionary
val maps to a list that includes key.
d: dict
Returns: dict
"""
inverse = dict()
for... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
def is_palindrome(word):
#this function is a palindrome
#A palindrome is a word that is spelled the same backward and forward, like “noon” and “redivider”.
if len(word) <= 1:
return True
if word[::1]== word[::-1]:
return True
return Fal... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
def chop(list):
#this function takes a list, modifies it by removing the first and last elements, and returns None.
del list[0]
del list[-1]
if __name__ == "__main__":
list = [1,2,3,4,5,6,7,8,9]
print chop(list) |
def main():
numbers = get_numbers()
print_number_facts(numbers)
usernames = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface',
'BaseStdIn', 'Command', 'ExecState', 'InteractiveConsole', 'InterpreterInterface', 'StartServer',
'bob'... |
"""
Code to simulate using taxis.
"""
from prac_08.taxi import Taxi
from prac_08.silver_service_taxi import SilverServiceTaxi
def main():
total_fare = 0
current_taxi = None
taxis = [Taxi("Prius", 100), SilverServiceTaxi("Limo", 100, 2), SilverServiceTaxi("Hummer", 200, 4)]
print("Let's Drive")
pr... |
# Exercise 3:
# Create a loop that quits with ‘q’
#
# Extra Credit: Make the loop quit with a user defined input
def main():
input1= input("Press q to quit")
iQuit= input("Enter your Quit phrase")
while(input1 != iQuit): #"q"):
input1=input("Press q to quit")
if __name__ == '__main__':
mai... |
def sumOfMultiples(upto):
# sum = 0
# for x in range(upto):
# if x % 3 == 0 or x % 5 == 0:
# sum += x
# return sum
return sum([x for x in range(upto) if x % 3 == 0 or x % 5 == 0 ])
print(sumOfMultiples(10))
|
def move_zeros(array):
b,c = [],[]
for i in range(len(array)):
if array[i] == (0 or 0.0) and not(array[i] is False) :
b.append(int(array[i]))
else:
c.append(array[i])
return (c+b) |
def iq_test(numbers):
odd =[]
even=[]
for i in [int(i) for i in numbers.split()] :
odd.append(i) if i%2 else even.append(i)
return 1 + [int(i) for i in numbers.split()].index(odd[0]) if len(odd) < 2 else 1 +[int(i) for i in numbers.split()].index(even[0]) |
import re
regex = input('Enter Regular Expression: ')
fhandle = open("mbox-short.txt")
count = 0
for line in fhandle:
x = re.findall(regex, line)
if len(x) > 0:
count = count + 1
print('The expression was found', count, 'times')
|
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# We use the TF helper function to pull down the data from the MNIST site
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# x is placeholder for the 28 X 28 image data
x = tf.placeholder(tf.float32, shape=[None, 784])
#... |
"""
Python MySQL Drop Table
Delete a Table
You can delete an existing table by using the "DROP TABLE" statement:
"""
#Example
#Delete the table "customers":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = ... |
"""
Python MySQL Create Database
Creating a Database
To create a database in MySQL, use the "CREATE DATABASE" statement:
"""
#Example
#create a database named "mydatabase":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.curs... |
"""
Smallest Subarray with a given sum
Given an array of positive numbers and a positive number ‘S’, find the length of the smallest subarray whose sum is greater than or equal to ‘S’. Return 0, if no such subarray exists.
Example 1:
Input: [2, 1, 5, 2, 3, 2], S=7
Output: 2
Explanation: The smallest subarray with a s... |
#!/usr/bin/python3
import numpy as np
print(' \n REMOVE DUPLICATES \n ')
def remove_dup_in_dict(dct):
lst = []
lst = list(dct)
return lst
def remove_dup_in_list(lst):
lst.sort()
i = len(lst) - 1
while i > 0:
if lst[i] == lst[i-1]:
lst.pop(i)
i -= 1
return lst
def remove_dup_in_ar... |
'''
How do we compute the indices for an array in Python, at which a certain
condition is satisfied
'''
import numpy as np
def first_test(condition, arr):
print('\n *** FIRST TEST *** ')
#true_indexes is a tuple we need to take its first arg.
true_indexes = np.where(condition)
print(' True indexes in ... |
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.output(11, GPIO.LOW)
GPIO.setup(13, GPIO.OUT)
GPIO.output(13, GPIO.LOW)
GPIO.setup(15, GPIO.OUT)
GPIO.output(15, GPIO.LOW)
while(True):
mode = int(input('Please Input Number : '))
GPIO.output(11, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
GPI... |
for i in range(1,100):
if i % 3 == 0:
print "fizz"
elif i % 5 == 0:
print "buzz"
elif i % 3 == 0 && i % 5 ==0:
print "fizzbzz"
elif i % 3 != 0 && i % 5 != 0:
print i |
# 为tuple中每个元素命名
## 定义一系列数值常量
NAME,AGE,SEX,EMAIL = range(4)
student = ('Jim',16,'male','jime@gmail.com')
print(student[EMAIL])
## 使用namedtuple代替tuple
from collections import namedtuple
Student = namedtuple('Student',['name','age','sex','email'])
s = Student('Jim',16,'male','jime@gmail.com')
print(s.name) # 可以直接用... |
"""Represents a dataset, linking a unique ID to a set of dataset states."""
from .hash import hash_dictionary
class Dataset:
"""
A dataset, linking a dataset ID to a state and a base dataset.
Parameters
----------
state_id : str
ID of the dataset state of this dataset.
state_type : s... |
#!/usr/bin/python3
"""Iterating in Reverse
Complete!
"""
if __name__ == '__main__':
a = [1, 2, 3, 4]
for x in reversed(a):
print(x)
|
#!/usr/bin/python3
"""Unpacking a Sequence into Separate Variables
Complete!
"""
if __name__ == '__main__':
p = (1, 2, 3)
x, y, z = p
print(x)
print(y)
print(z)
|
#!/usr/bin/python3
"""Transforming and Reducing Data at the Same Time
Complete!
"""
if __name__ == '__main__':
# Output a tuple as CSV
s = ('ACME', 50, 123.45)
print(','.join(str(x) for x in s))
# Data reduction across fields of a data structure
portfolio = [
{'name': 'GOOG', 'shares': 5... |
import re
def TRANSCRIPTION():
prompt = input("[1] = DNA to RNA \n[2] = RNA to DNA \n Option: ")
option = int(prompt)
Seq = input("Enter sequence: " )
seq = Seq.upper()
NTS = ''
if option == 1:
for nt in seq:
if nt == 'T':
NTS = NTS + 'U'
e... |
#!/usr/bin/env python
import sys
import itertools
import os
from itertools import groupby
from operator import itemgetter
# Function definitions
def pagination(pag, interv, my_dic, sorting_dic, mode, length_dic):
print("\nUsing pagination function...")
# Pagination
if pag:
if int(interv) > int(le... |
import numpy as np
import cv2
def filter_pixels_by_distance(x, y, distance):
filter_mask = np.sqrt(x**2 + y**2) < distance
new_x = x[filter_mask]
new_y = y[filter_mask]
return new_x, new_y
# Identify pixels above the threshold
# Threshold of RGB > 160 does a nice job of identifying ground pixels only
... |
#This project is about creating a program that can determine the grade and test average of give test scores.
#4/1/2018
#CTI-110 P5HW1 : Test Average and Grade
#Elianna Hunter
def main():
score1 = 0.0
score2 = 0.0
score3 = 0.0
score4 = 0.0
score5 = 0.0
avg = 0.0
score1 = ... |
#CTI-110
#P4LAB: Nested Loops
#Elianna Hunter
#3/22/2018
import turtle
wn = turtle.Screen()
t = turtle.Turtle()
t.pensize(4)
t.pencolor("pink")
t.shape("turtle")
t.left(180)
for i in (1,2,3,4,5):
for j in (1,2,3,4):
t.forward(90)
t.right(90)
t.forward(100)
t.left(73... |
nombre = input("Ingresa tu nombre: ")
print(f"Tu nombre es: {nombre}") |
import argparse
import os
from lib.string_formatter import format_text
DEFAULT_LINE_SIZE = 40
"""
Configuração dos argumentos de linha de comando:
--line-size: Tamanho máximo permitido para as linhas. O padrão é 40 caracteres.
--justify: Flag opcional que informa se o texto deve ser justificado ou não. P... |
data = """o - x
o x x
x o o"""
field = [line.split() for line in data.split('\n')]
def tic_tac_toe(field):
x = False
o = False
y1, y2, y3, di1, di2 = '', '', '', '', ''
count = 0
for elem in field:
elem = ''.join(elem)
count += 1
if elem == 'xxx':
x = True
... |
def squared():
st = ' '
st0 = ''
check = False
for i in range(11, 100):
if i % 10 == 0:
pass
else:
if (i + 1) % 10 == 0:
check = True
else:
pass
i = str(i ** 2)
if (len(i) == 3) and (check != True... |
under_20 = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
big_num = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
def number_in_engli... |
# V27 poo metodo constructor
# ********Muy importante este video******
class Coche():
def __init__(self): #asi es un metodo constructor en python
self.__largoChasis=250 # __ analogo de private
self.__anchoChasis=120
self.__ruedas=4 # __ analogo de private
self.__enmarcha=False
#colocamos self a aquel... |
# V8 Tuplas
#se cren con () se leen con []
miTupla=("Lunes","Martes","Miercoles","Jueves","Viernes","Sabado","Domingo")
print(miTupla[2])
print(miTupla[:])
#Convertir una tupla en una lista
miLista=list(miTupla)
#Convertir una list en una tupla
miTupla2=tuple(miLista)
print("Lunes" in miTupla2) # true si ex... |
#Funciones con parametros V6
#sin return
# def suma(num1, num2):
# print(num1+num2)
# #
# suma(5,7)
#Funciones con parametros V6
#con return
def suma2(num1, num2):
suma=num1+num2
return suma
#
print(suma2(5,7))
|
import numpy as np
import pandas as pd
X_train_df = pd.read_csv('../data/train_X.csv', header=None)
Y_train_df = pd.read_csv('../data/train_Y.csv', header=None)
"""
Lets say, we take in to account last N days of data. Our first input will be
0 to N-1, 2nd input will be 1 to N and our last set will be len(df)-N to len... |
import unittest
import main
class TestCalculator(unittest.TestCase):#unittest module provides a set of tools for constructing and running scripts, we will test features of online calculator in this case
def setUp(self):#setUp , when unittest module is used and it enables application to test
main.app.testing = ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 20 10:04:38 2021
@author: David Stoneking
"""
# Define a function that takes one integer argument and returns logical value true or false depending on if the integer is a prime.
# Per Wikipedia, a prime number (or a prime) is a natural number greater than 1 tha... |
# -*- coding: utf-8 -*-
"""
@author: Vivian
"""
from hangman import Hangman
"""
Game() is the entrance and contains different games for users to play(currently only hangman)
Based on user's choice, the Game class will start the game and generate a new round
"""
class Games:
# game ids for hangman
HANGMAN... |
def encrypt_vigenere(plaintext, keyword):
"""
>>> encrypt_vigenere("PYTHON", "A")
'PYTHON'
>>> encrypt_vigenere("python", "a")
'python'
>>> encrypt_vigenere("ATTACKATDAWN", "LEMON")
'LXFOPVEFRNHR'
"""
encrypted = list()
for i in range(0, len(plaintext)... |
import time
import re
import os
from datetime import datetime
def karma_yesterday():
# Create karma.txt if it doesn't exist
if not os.path.isfile("karma.txt"):
open("karma.txt", "a").close()
# Get all the karma data from the file into a list
with open("karma.txt", "r") as karmafile:
ka... |
listaObecnosci = [
'iksiński', # 0
'kowalski', # 1
'zimny', # 2
'świtaj' # 3
]
print(listaObecnosci[3])
listaObecnosci.append('aniserowicz')
print(listaObecnosci)
listaObecnosci.insert(0, 'dziekan')
print('z dziekanen:')
print(listaObecnosci)
listaObecnosci.extend(['a', 'b', 'c'])
print(listaOb... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 30 11:28:13 2021
@author: rafsh
"""
name= ['Rafshan','Bin','Razzak'];
print(name);
name.append('Mahi');
print(name);
name.insert(2, 'habijabi');
print(name);
name.pop(2);
print(name);
print(len(name));
number=[1,51,8,16,7,5];
lst=number... |
from globals import *
from math import sqrt
class Game:
"""One game."""
def __init__(self, MOV, isWon, oppName, oppRating, home, day):
"""Initialize the game."""
self.MOV = MOV
self.day = day
self.isWon = isWon
self.home = home
self.oppName = oppName
... |
def midpoint(low,high):
return (low+ high)/2
print "Think of a number between 1 and 100"
low = 1
high = 100
while True:
guess = midpoint(low, high)
print "I guess", guess
print "1. Way too low"
print "2. Too low"
print "3. Too high"
print "4. Way too high"
print "5. Correct!"
input = int(raw_inp... |
from random import randint
def shuffle():
for i in xrange(100):
first = randint(0,51)
second = randint(0,51)
if first != second:
deck[first], deck[second] = deck[second], deck[first] # python swapping is super easy!
deck = []
# Adds the cards
for card in xrange(1,14): # one for each number (A... |
""" playgame.py
Contains the Connect 3 game playing application.
This file forms part of the assessment for CP2410 Assignment 2
************** ENTER YOUR NAME HERE ****************************
"""
from connect3board import Connect3Board
from gametree import GameTree
from timeit import default_timer as timer
def ma... |
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> #tipos de variables
>>> num1=3
>>> num1
3
>>> print(num1)
3
>>> letras="hola mundo"
>>> letras
'hola mundo'
>>> print(letras)
hola mundo
>>> #imprim... |
#!/usr/bin/python3
class Person:
def __init__(self, first, middle, last, age):
self.first = first
self.middle = middle
self.last = last
self.age = age
def __str__(self):
return self.first + ' ' + self.middle + ' ' + self.last + \
str(self.age)
def initials(self):
return self.first[0] + self.middle[0] ... |
#!/usr/bin/python3.4
grade = 99
if grade >= 90:
letterGrade = 'A'
elif grade >= 80:
letterGrade = 'B'
elif grade >= 70:
letterGrade = 'C'
elif grade >= 60:
letterGrade = 'D'
else:
letterGrade = 'F'
print(letterGrade)
|
class Circle(object):
"""circle class"""
#--------------- static variables
_all = []
_pi = 3.14159
#--------------- static methods
@staticmethod
def totalArea():
total = 0
for c in Circle._all:
total += c.area()
return total
@staticmeth... |
import unittest
def safe_int(obj):
try:
return int(obj)
except (ValueError,TypeError):
return "ErrorCast"
def throw_exception(value1,value2,value3):
"""throw tuple as the argument of exception"""
raise Exception(value1,value2,value3)
def not_implemented_method():
raise No... |
import unittest
# ------------------------------- Template Pattern
class TemplateBase(object):
def templateMethod(self):
return self.subMethod1() + self.subMethod2()
def subMethod1(self):
raise NotImplementedError("must override in derived class")
def subMethod2(self):
ra... |
import unittest
class MutableImmutableTest(unittest.TestCase):
def testIncrementImmutable(self):
a = 1
b = a
oldid = id(a)
a += 1 # silently create a new object, and point a to that new object
newid = id(a)
# a points to a new object
# b st... |
class MyTime(object):
def __init__(self,hour,minute):
self._hour = hour
self._minute = minute
def __str__(self):
return "%d:%d"%(self._hour,self._minute)
def __add__(self,other):
return self.__class__(self._hour + other._hour,self._minute + other._minute)
... |
class Person(object):
def __init__(self,ssn,name):
self._ssn = ssn
self._name = name
def __eq__(self,rhs):
if self is rhs:
return True
elif isinstance(rhs,Person):
return (self._ssn == rhs._ssn) and (self._name == rhs._name)
else:
... |
import unittest
class GroupedArgsTest(unittest.TestCase):
# ---------------------- for test list arguments
def _sum(self,*args):
size = len(args)
sum = args[0]
for index in range(1,size):
sum += args[index]
return sum
def testTupleParameter(self):
... |
# name = 'Emre Çat'
# for i in name:
# print(i)
# 62 for döngü uygulama
sayilar=[1,3,5,7,9,12,19,21]
# #1. soru
#
# for i in sayilar:
# if i%3==0:
# print(i)
#2. soru
# toplam=0
# for i in sayilar:
# toplam+=i
# print(toplam)
ürünler=[
{'name':'samsung s6','price': '3000... |
x,y,z=2,5,10
numbers=1,5,7,10,6
sayi1=input("1. sayiyi giriniz")
sayi2=input("2.sayiyi giriniz")
carpim=int(sayi1)*int(sayi2)
print("sonuc:",carpim-(x+y+z))
print(y//x)
toplam=x+y+z
print(toplam%3)
x,*y,z=numbers
z**=2
print(f"z nin değeri : {z}")
ytoplam=y[0]+y[1]+y[2]
print(ytoplam) |
import pandas as pd
import numpy as np
data={
'Column1':[1,2,3,4,5],
'Column2':[10,20,13,45,25],
'Column3':["abc","bca","ade","cba","dea"]
}
df=pd.DataFrame(data)
result=df
result=df['Column2'].unique() # tekrarlamayan bilgileri gösterir
result=df['Column2'].nunique() # kaç tane farklı değer... |
# name=input("lütfen isminizi giriniz.")
# age=int(input("Lütfen yasınızı giriniz"))
# educatelevel=input("lütfen eğitim seviyenizi giriniz.")
# if (age>=18 and (educatelevel=="üni" or educatelevel=="lise")):
# print("Ehliyet alabilirsiniz.")
# else:
# print("ehliyet alma koşulları sağlanamadı.")
#2 ... |
# # class
# class Person:
# #pass # içi bir bir class oluşturup hata almamak için içines pass yazıyoruz
# # class attributes
# address='no information'
# #constructor (yapıcı method)
# def __init__(self, name, year): # self p1,p2 gibi classtan türetilen nesneleri temsil eder
... |
import pandas as pd
df=pd.read_csv('imdb.csv')
# 1- Dosya hakkındaki bilgiler
result=df
result=df.info
result=df.columns
# 2- ilk 5 kayıt
result=df.head(5)
# 3- ilk 10 kayıt
result=df.head(10)
# 4- son 5 kayıt
result=df.tail(5)
# 5- son 10 kayıt
result=df.tail(10)
# 6- Sadece Movie_Title column
resu... |
class Person():
def __init__(self,fname,lname):
self.ad=fname
self.soyad=lname
print("Person Created")
def who_am_i(self):
print('I am a Person')
class Student(Person):
def __init__(self,dene1,dene2,number):
Person.__init__(self,dene1,dene2) ##### P... |
name='Çınar'
surname="deneme"
print("my name is {} {}".format(name,surname)) |
#!/usr/bin/env python3
"""Program that calculates the probability density
function of a Gaussian distribution"""
import numpy as np
def pdf(X, m, S):
"""Function that calculates the probability density
function of a Gaussian distribution"""
if type(X) is not np.ndarray or len(X.shape) != 2:
return... |
#!/usr/bin/env python3
"""Program that returns the list of school having a specific topic"""
def schools_by_topic(mongo_collection, topic):
"""Function that returns the list of school having a specific topic"""
all_items = mongo_collection.find()
docs = []
doc_filter = []
for elem in all_items:
... |
#!/usr/bin/env python3
"""Program that calculates the minor matrix of a matrix"""
def determinant(matrix):
"""Function that calculates the determinant of a matrix"""
if type(matrix) is not list or not matrix:
raise TypeError('matrix must be a list of lists')
for data in matrix:
if type(dat... |
#!/usr/bin/env python3
"""Program that performs matrix multiplication"""
def mat_mul(mat1, mat2):
"""Function that performs matrix multiplication"""
mat1m = len(mat1)
mat1n = len(mat1[0])
mat2m = len(mat2)
mat2n = len(mat2[0])
result = []
if mat1n == mat2m:
for x in range(mat1m):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.