text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python3
#zadanie: min,max, pocet prvkov, suma, prvy a posledny prvok vektorov
value = (7, 1, 2, 87, 6)
# value2 = (5, 7, 99, 101)
# minimum = min(value)
# maximum = max(value)
suma = sum(value)
#maximum
maximum = value[0]
for i in value:
if i > maximum:
maximum = i
print(f'maximum j... |
#!/usr/bin/python3
import re
# words = ('a gray bird', 'grey hair', 'great look')
words = ('deep', 'leak','look', 'meet', 'seen','seed', 'good')
pattern = re.compile(r'[^oe]{2}') # [^xy] neobsahuje, negacia hladaneho kriteria
for word in words:
if re.search(pattern, word):
print('{} matches'.format(wor... |
#!/usr/bin/python3
from prettytable import from_csv
with open("data2.csv", "r") as fp:
x = from_csv(fp)
x.align["City name"] = "l"
x.align["Area"] = "r"
x.align["Population"] = "r"
x.align["Annual Rainfall"] = "r"
# x.sortby = 'Population'
print(x.get_string(sortby='Population', sort_key=lambda row: int(r... |
#!/usr/bin/env python3
vals = "1@2@3@4@5@6@7"
### zadanie: rozdelit string na jednotl znaky a vypisat sucet cisel
splitted = vals.split("@")
print(splitted)
_sum = 0
for i in splitted:
_sum += int(i)
print(_sum)
|
def main():
smileString = f" \U0001f600"
happy = int(input("How happy are you from 1-10?"))
print(f"{smileString} \n" * happy)
main() |
import math
cou = 0
def is_prime(n):
for i in range(2,int(math.sqrt(n))+1):
if n%i == 0:
return False
return True
x = int(input())
if is_prime(x):
print(1)
else:
for i in range(2,int(x/2)+1):
if x%i == 0:
cou +=1
print(cou+1)
|
inpt = int(input())
n = 0
while n!=1:
inpt +=1
x = str(inpt)
if x[0] != x[1] and x[0] != x[2] and x[0] != x[2] and x[0] != x[3] and x[1] != x[2] and x[1] != x[3] and x[2] != x[3]:
n +=1
print(inpt) |
size = int(input())
x = 0
ls1 = []
ls2= []
for i in range(size):
x = int(input())
div = int(x/2)
sum_even = int(div*(div+1))
odd_number = (div-1)*(div - 1)
sum_odd = 0
if (sum_even - odd_number )%2 == 0:
print("NO")
else:
print("YES")
for i in range(2,x+1,2):
... |
size = int(input())
Mishka = 0
Chris = 0
for i in range(size):
a,b = input().split(" ")
a = int(a)
b = int(b)
if a>b:
Mishka +=1
elif a<b:
Chris +=1
else:
pass
if Mishka>Chris:
print('Mishka')
elif Mishka<Chris:
print('Chris')
else:
print('Friendship is mag... |
perticipent,pen,note_book = input().split(" ")
perticipent = int(perticipent)
pen = int(pen)
note_book = int(note_book)
if perticipent<=pen and perticipent<=note_book:
print("Yes")
else:
print("No")
|
from collections import Counter
def solution(s):
answer = []
s = s[1:-1]
tmp = []
num = []
ss = ''
check = False
for i in s:
if i == '{':
check = True
continue
if i == '}':
tmp.append(ss)
num.extend(tmp)
tmp = []
... |
result = 0
for i in range(int(input())):
num = input()
a,b = int(num[:-1]),int(num[-1])
result += a**b
print(result) |
class Node:
def __init__(self, data=0):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = Node(0)
self.length = 0
def push(self, data):
node = self.head
newNode = Node(data)
while node.next != None:
node... |
import sys
class Queue:
def __init__(self):
self.front = 0
self.back = 0
self.size = 0
self.li = []
def ssize(self):
return self.size
def empty(self):
return 1 if self.size == 0 else 0
def push(self, data):
#self.li[self.back] = data
se... |
def getdiv(n):
thr = n//2
ans = 0
for i in range(1,n+1):
if i**2 > n:
break
else:
if n % i == 0:
ans += i
if i**2 < n:
ans += n//i
return ans
for i in range(int(input())):
N = int(input())
ans = 0
fo... |
def isNum(li,length):
if len(li) == length and li.isdigit():
return True
return False
def solution(phone_number):
num = phone_number.split('-')
# rule 2
if len(num) == 1 and num[0][:3] == '010':
rest_num = num[0][3:]
if isNum(rest_num,8):
return 2
ret... |
#!/usr/bin/env python
# -*- conding:utf-8 -*-
# Author:Tandatoua
# FileName:SinglyLinked.py
# Python Version:Python 3.6
#Code Specification:pep8
# Desc:Singly Linked
class SinglyLinkNode(object):
def __init__(self, data):
self.data = data
self.next = None
# Traversing a linked list.
def trave... |
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if len(nums)==1:
return
#3 way partitioning
left= mid = 0
right= len(nums)-1
while(mid <= right):
... |
def find_smallest(array):
smallest = array[0]
smallest_index = 0
counter = 0
for i, element in enumerate(array):
counter += 1
if element < smallest:
smallest = element
smallest_index = i
return smallest_index, counter
def find_biggest(array):
biggest = a... |
import random
import time
import collections
def insertSort(l):
for j in range(len(l)):
key = l[j]
i = j - 1
while i >= 0 and l[i] > key:
l[i + 1] = l[i]
i = i - 1
l[i + 1] = key
return l
def mergeSort(l):
if len(l) >1:
mid = len(l) // 2... |
'''
Solution:
1. Iterate until dividend is less than divisor, and keep updating dividend by maintaining an inner iteration.
2. In the inner iteration, iterate until, dividend is less than divisor shifted left shift times and update dividend
accordingly.
3. Add to quotient, number of shifts shifted left to 1 afte... |
"""
SLAL: Vector Utility Functions
by dysnsne
(c)opyleft
"""
from vector import Vector
# utility functions for vectors
def list2vector(L):
"""Turn a list of length n into a n-vector"""
return Vector(set(range(len(L))), { k : v for (k, v) in enumerate(L)})
def vector2list(V):
""" Turn vector into list. ""... |
max = -999; min = 101
cond_clim = []
salir = False
while not salir:
quedarse = raw_input("Ingrese 'si' para seguir o 'no' para salir: ")
if quedarse == "si":
temp = input("Ingrese temperatura: ")
hum = input("Ingrese humedad: ")
prob_lluv = input("Ingrece la probabilidad de lluvias: ")
... |
carac = raw_input("Ingrese una letra: ")
vocales = "AaEeIiOoUu"
consonantes = "BCDFGHJKLMNPQRSTVWXYZbcdfghijklmnpqrstuxyz"
def letra(carac, vocales, consonantes):
for i in vocales:
if i == carac:
return 1
for i in consonantes:
if i == carac:
return 2
if letra(carac, vocal... |
def hello():
print("Hello!")
hello()
def user_age_in_seconds():
user_age = int (input("Enter you age: "))
age_seconds = user_age * 365 * 24 * 60 * 60
print(f"Your age in seconds is {age_seconds}.")
print("Welcome to the age in seconds program!")
user_age_in_seconds()
print("Goodbye!")
friends = ["... |
def divide(dividend, divisor):
if divisor == 0:
raise ZeroDivisionError("Divisor cannot be 0.")
return dividend / divisor
# grades = ["asd", 99,85, 100]
# grades = []
grades = [88, 99, 85, 100]
print("Welcome to the average grade program.")
try:
average = divide(sum(grades), len(grades))
except... |
# List
l = ["Bob", "Rolf","Anne"]
# Tuple
t = ("Bob", "Rolf","Anne")
# Set
s = {"Bob", "Rolf","Anne"}
print(l[0])
print(t[0])
# print(s[0])
l[0] = "Pepe"
# t[0] = "Pepe"
l.append("Pepito")
l.remove("Pepe")
print(l)
s.add("Smith")
s.add("Smith")
print(s) |
from itertools import permutations
def parse_input(file_name):
return [x.rstrip().split(' ') for x in open(file_name).readlines()]
def permute_string(value):
return [''.join(x) for x in permutations(value, len(value))]
def is_valid_passphrase_solution_one(passphrase):
words = set()
for word in pas... |
from tkinter import *
root = Tk()
def log():
if(Login.get()=="123"):
root2 = Tk()
root.destroy()
Passwort = Label(root2, text="Welcome")
Passwort.place(x=20, y=20)
Login = Entry(root, show="*")
Login.place(x=50, y=50, width=100)
Passwort = Label(root, text="Login")
Passwort.place... |
import numpy as np
class Snake():
def __init__(self, board_size):
self.board_size = board_size
self.length = 1
self.body = [(0, 0)] # replace with something random
self.direction = 0
self.right = 0
self.left = 1
self.up = 2
self.down = 3
def addNode(self, prev_tail):
self.length += 1
self.b... |
#{key:value for (key, value) in iterable}字典推导
lst = [1, 2, 3, 4, 5]
res = {i: 'python'+str(i)+'期' for i in lst if i > 0}
print(res) |
#!/usr/bin/env python
def print_board(board):
for row in board:
for col in row:
print(col, end=" ")
print("\n")
def find_empty_square(board):
"""
Return a tuple containing the row and column of the first empty square
False if no squares are empty
"""
for i, row in... |
board = [" " for i in range(9)]
def print_board():
row1 = "| {} | {} | {} |".format(board[0], board[1], board[2])
row2 = "| {} | {} | {} |".format(board[3], board[4], board[5])
row3 = "| {} | {} | {} |".format(board[6], board[7], board[8])
# | is given for splitting of the row data and {} refers to plac... |
# 1. Creates multiple processes
# 2. Processes can't share global variables in a straigh-forward way
# 3. Utilizes all the cores
# 4. To shared some variables across the processes use
# multiprocessing.Queue
import multiprocessing
import time
import random
def hello(n):
time.sleep(random.randint(1, 3))
pri... |
#
# Convert most files with wrong encoding (mix of utf-8 and latin-1) into utf-8 encoded csvs
#
import pandas as pd
import io
file_name = "RSEG_for_edd_v1.csv"
output_file = file_name.replace(".csv", "_final.csv")
delimiter = b","
def read_data(file_name):
data = []
with open(file_name, "rb") as f:
... |
# Conversi satuan Celcius ke R F K
# Conversi satuan temperatur
print("\nProgram Konversi Temperature\n")
celcius = float(input('Masukkan Suhu dlm Celcius: '))
print("Suhu adalah: ", celcius, "Celcius")
#Reamur
reamur = (4 / 5) * celcius
print("Suhu reamur: ", reamur, "Reamur")
#Fahrenheit
fahrenheit ... |
# assignment 2 solution
def max_of_three(x1,x2,x3):
if x1 > x2:
intermediate_maximum = x1
else:
intermediate_maximum = x2
if intermediate_maximum < x3:
maximum = x3
else:
maximum = intermediate_maximum
return maximum
# testing the function
print( max_o... |
import matplotlib.pyplot as plt
inputFile = "input.txt"
# The node points on the computational domain
"""
CONST_PointsMatrix = [[(-1.,1.),(1.,1.)],\
[(-1.,-1.),(1.,-1.)]]
"""
CONST_PointsMatrix = [[(-1.,-1.),(-1.,0.),(-1.,1.)],\
[(0.,-1.),(0.,0.),(0.,1.)],\
[(1.,-1.),(1.,0.),(1.,1.)]]
CONST_Dim... |
######################################
# Author: Daniel S. Lee
# Date: 12-09-17
# Note: 2D Peak Finder
######################################
import numpy as np
def max(array):
array = array.tolist()
chain = [i[0] for i in array]
m = np.max(chain)
return [(p, v) for p, v in enumerate(chain) if m == v][0]
def pea... |
"""
Implementation of K-closest points to the origin
"""
from timeit import timeit as tm
def dist(c):
return sum(v ** 2 for v in c) ** (1 / 2)
# Initial approach
def k_closest_origin(coords):
return sorted([dist(c), c] for c in coords)[0][1]
if __name__ == '__main__':
data = [(-2, 4),
( 0,-2),
(-1, 0),
... |
#!/usr/bin/python3
for i in range(0, 100):
# condition to the last digit and set the line jump
if i == 99:
print(i)
break
# 0:02d, zero is added at position 2
print("{0:02d}".format(i), end=", ")
|
#!/usr/bin/python3
"""
Square
"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
"""class square that inherits.
"""
def __init__(self, size):
"""initial method that take the size of square.
Agrs:
size: size of square.
"""
self.intege... |
#!/usr/bin/python3
""" This script takes in a letter and sends a POST request to
http://0.0.0.0:5000/search_user with the letter as a parameter.
"""
import requests
import sys
from requests.exceptions import HTTPError
if __name__ == "__main__":
if len(sys.argv) > 1:
obj = {"q": sys.argv[1]}
else:
... |
#!/usr/bin/python3
for i in range(97, 123):
# condition to not print the vocal e or q
if i == 101 or i == 113:
continue
# chr return a character, as would be in ASCII code
print("{}".format(chr(i)), end="")
# delete the line jump
|
#!/usr/bin/python3
"""
Write in a file.
"""
def write_file(filename="", text=""):
"""function that writes a text in a file and if the file
does not exist, it creates it.
Args:
filename: name of file
text: text a write in the file
Return the character number.
"""
with open(file... |
#!/usr/bin/python3
"""
Student.
"""
class Student:
"""class that defines a student.
"""
def __init__(self, first_name, last_name, age):
"""initial method that take the arguments.
Args:
first_name: name of student
last_name: last name of student
age: ... |
#!/usr/bin/python3
def uniq_add(my_list=[]):
new_list = []
sum = 0
for i in my_list:
# Condition to watch if element i, is within new_List
if i in new_list:
pass
else:
new_list.append(i)
sum += i
return sum
|
import functools
class employee:
def __init__(self,id,name,desig,mail,sal):
self.id=id
self.name=name
self.desig=desig
self.mail=mail
self.sal=sal
def printvalues(self):
print(self.id,self.name,self.desig,self.mail,self.sal)
f=open("empdata")
emp=[]
... |
num=int(input("Enter number"))
res=0
while(num>0):
digit=(num%10)
res=(digit**3)+res
num=num//10
print(res)
|
lowlimit=int(input("Enter low limit:"))
limit=int(input("Enter high limit"))
while(lowlimit<=limit):
print(lowlimit)
lowlimit+=1
|
#ELEMENTS SEARCHING
lst=[10,11,12,13,14,15,16,17]
element=int(input("Enter element for searching"))
flag=0
for i in lst:
if (i==element):
flag=1
break
else:
pass
if(flag==1):
print("element in list")
else:
print("element not in list") |
lst=[2,4,3]
res=[]
c=1
for i in lst:
j=i**c
res.append(j)
c+=1
print(res)
|
lst=[5,40,80,15]
#Normal method
squarelist=list(map(lambda x:x**2,lst))
print(squarelist)
#List comprehensive method
square=[(i**2)for i in lst]
print(square)
#PRINT PAIRS
lst=[1,2,3]
lst2=[4,5,6]
#Normal method
for i in lst:
for j in lst2:
print((i,j))
#List Comprehensive method
pairs=[(i,j) for i in ... |
"""General definitions that are used for cleaning, preparing and processing the FerPlus and AffectNet dataset."""
import _pickle as cPickle
import bz2
from math import ceil
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import model_selection
from tensorflow.keras.preprocessing.ima... |
#!/usr/bin/env python3
#11/10/2018 11:10 AM
#sound playback using kivy.
from pygame import mixer
from kivy.base import EventLoop
from bt import *
#NOTE: In order for sounds to play correctly we have to use an EventLoop
# with a Listener. The listener needn't do anything and the EventLoop.idle()
# function must be c... |
class Fraction(object):
def __init__(self, num, den = 1):
common = self.gcd(num, den)
# Pogramming exercises 5
if type(den) != int or type(den) != int:
raise ValueError("Values must be integers")
if den == 0:
raise ValueError("Division by Zero")
# Pogramming exercises 6
if num < 0 or den < 0:
... |
class Range(object):
def __init__(self, start, stop = None, step = 1):
if step == 0:
raise ValueError('step cannot be zero')
if stop is None:
start, stop = 0, start
self.__length = max(0, (stop − start + step − 1) // step)
self.__start = start
self.__step = step
def __len__(self):
return self.... |
class StudentRecord(object):
def __init__(self, student_id, first_name, last_name, year, gpa):
self._year_dct = {1 : 'Freshman', 2 : 'Sophomore', 3 : 'Junior', 4 : 'Senior'}
self.id = student_id
self.first_name = first_name
self.last_name = last_name
self.year = self._year_dct[year]
self.gpa = gpa
class ... |
def selection_sort(lyst, profiler):
i = 0
while i < len(lyst) - 1: # Do n - 1 searches
minIndex = i # for the largest
j = i + 1
while j < len(lyst): # Start a search
profiler.comparison()
if lyst[j] < lyst[minIndex]:
... |
print 'Welcome to the GPA calculator.'
print 'Please enter all your letter grades, ones per line.'
print 'Enter a blank line to designate the end.'
points = {'A+' : 4.00, 'A' : 4.00, 'A-' : 3.67, 'B+' : 3.33, 'B' : 3.00, 'B-' : 2.67,
'C+' : 2.33, 'C' : 2.00, 'D+' : 1.33, 'D' : 1.00, 'F' : 0.0}
num_courses = 0.0
t... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
suma=0
n=(int(raw_input("Mostrar la suma de los primeros ..."))
for ele in n:
suma+=ele
print "Suma Total = ",suma
|
#!/usr/bin/env pyhton
#-*- coding: utf-8 -*-
suma=0
cuenta=0
a=int(raw_input("Introduce numero : "))
while(a>0):
suma =suma + a
cuenta =cuenta + 1
a=int(raw_input("Introduce numero : "))
print cuenta
print suma
|
#!/usr/bin/env python
#-*- coding: utf-8 -*-
def fun(x,y):
return x+y
x=int(raw_input("Introduce primer numero : "))
y=int(raw_input("Introduce segundo numero : "))
z=fun(x,y)
print "Suma = ",z
|
import turtle
def draw_square(mangla):
side = 4
while side:
mangla.forward(100)
mangla.right(90)
side = side - 1
def draw_h(t):
t.penup()
t.sety(250)
t.setx(-280)
t.pendown()
t.right(90)
t.forward(100)
t.left(90)
t.forward(20)
t.left(90)
t.forward(40)
t.right(90)
t.forward(40)
t.right(90)
t.forw... |
def generate_line(symbol, offset_space, symbol_count):
offset = " " * offset_space
content = ' '.join(symbol_count * f"{symbol}")
return f"{offset}{content}"
def draw_line(symbol, offset_space, symbol_count):
print(generate_line(symbol, offset_space, symbol_count))
def draw_rhombus(size):
for i ... |
# class Book:
# def __init__(self, content: str):
# self.content = content
#
#
# class Formatter:
# def format(self, book: Book) -> str:
# return book.content
#
#
# class Printer:
# def get_book(self, book: Book):
# formatter = Formatter()
# formatted_book = formatter.format(... |
from math import sqrt
def is_prime(number):
if number == 0 or number == 1:
return False
for num in range(2, int(sqrt(number)) + 1):
if number % num == 0:
return False
return True
def get_primes(list_of_numbers):
for number in list_of_numbers:
if is_prime(number):
... |
# change any text into handwritten text using Python
import pywhatkit as kit
import cv2
kit.text_to_handwriting("Python is very famous programming language available in the market",
save_to="handwriting_1.png")
img = cv2.imread('handwriting_1.png')
cv2.imshow("text_handwritten_",img)
cv2.waitKey(0)... |
import datetime
d1= datetime.date(2020,3,4)
print("d1: ",d1)
# replace month with 7
d2=d1.replace(month=7)
print('d2: ',d2) |
#Una función recursiva no es mas que una función
# que se llama a si misma dentro de si misma.
def suma(num1):
if num1 == 0:
return 0
return num1 + suma(num1 - 1)
def suma_ciclo(num1):
resultado = 0
while num1 != 0:
resultado = resultado + num1
num1 -= 1
return resultado
... |
# Estructura de transferencias
# transfieren el flujo del código (cambio en el flujo)
# Tipos de Transferencias
# break
# continue
# return
# break -> detener el flujo
# Ejemplo
while (True):
print("Hola")
if(True):
numero = int(input("Ingrese un número: "))
if (numero > ... |
"""
Classes to transform different data types for machine learning
author: Francesco Baldisserri
email: fbaldisserri@gmail.com
version: 0.6
"""
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.p... |
"""
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
... |
'''
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
Each element in the result must be unique.
The result can be in any order.
'''
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type n... |
"""
Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
"""
'''
>>> import math
>>> n=243
>>> tmp = math.log(n, 3)
>>> tmp
4.999999999999999
>>> math.log10(n) / math.log10(3)
5.0
'''
class Solution(object):
def isPowerOfThree(... |
import time
begin = time.time()
# exponentiation by squaring
def better_pow(x,n):
if n==1:
return x
elif n%2==0:
return better_pow(x*x,n/2)
else:
return x*better_pow(x*x,(n-1)/2)
# converts input to list of lists of 2 entries
pairs = [pair.strip().split(',') for pair in open("bas... |
#Name:Ethan Turner
#Date:September 9th 2016
#Description:A Trivia game of three questions that you can retake as many times as you want.
#Worth 10/10 points, all pieces done and a few extra prints for fun.
#This is the introduction
print("Welcome to Ethan's little trivia game! You will have three questions, and ... |
matriz = []
for i in range(0,10):
row = []
for j in range(0,10):
row.append(input())
matriz.append(row)
else:
for i in range(0,10):
print(matriz[i])
|
# This program calculate how many tiles you will need
# when tiling a wall or floor in m2.
lenght = float(input('Enter lenght: '))
width = float(input('Enter width: '))
area = lenght * width
tiles = area * 1.05
print('You need', tiles, 'tiles in m2.') |
# Щедрый посетитель
score = int(input("Введите сумму счета за обед: "))
print("Сумма счета :", score, "руб.")
first_tip = score * 15 / 100
second_tip = score * 20 / 100
print("Чаевые из расчета 15% : ", int(first_tip))
print("Чаевые из расчета 20% : ",int(second_tip))
|
# A procedure that takes in a string of numbers from 1-9 and
# outputs a list with the following parameters:
# Every number in the string should be inserted into the list.
# If a number x in the string is less than or equal
# to the preceding biggest number y, the number x should be inserted
# into a sublist. Continu... |
# Author: Jessica
""" --- Day 2: Inventory Management System ---
You stop falling through time, catch your breath, and check the screen on the device.
"Destination reached. Current Year: 1518. Current Location: North Pole Utility Closet
83N10." You made it! Now, to find those anomalies.
Outside the utility closet, yo... |
#!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that pers... |
# For each of the procedures defined below, check the box if the procedure always terminates for all inputs that are natural numbers (1,2,3...).
def proc1(n):
while True:
n = n - 1
if n == 0:
break
return 3
# yes, has a break and will reach 0
def proc2(n):
if n == 0:
return n
... |
# Takes a list as input, and returns the
# boolean True if the list is symmetric and False if it is not.
def symmetric(s):
items=len(s)
column=[]
digit=0
while digit<=items:
i=0
while i<items:
j=0
row= s[i]
# print row
while j<items:
... |
class Edureka:
def __init__(self):
self.pub = "Public attribute"
self._prot = "Protected"
self.__private = "Private"
self._percent = 0.3
def investment_returns(self, amount):
output = amount + amount * self._percent
print(int(output))
class EdurekaTwo:
x = ... |
my_dict = {
"Paul": "40",
"Kate": "19",
"Ben": "29",
"Clive": "56"
}
print(my_dict)
del my_dict["Ben"]
print(my_dict)
my_dict = {
"Paul": "40",
"Kate": "19",
"Ben": "29",
"Clive": "56"
}
for key in my_dict.keys():
print(f"key={key}")
print(f"value={my_dict[key]}")
print(sorte... |
import os
def backtracking_solve(grid):
# Find the next empty cell
cell = grid.get_empty_cell()
if not cell:
print('== Puzzle Solved ==')
print(grid)
return True
for value in range(1, 10):
if grid.check_validity(cell, value):
cell.value = value
if... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 19 10:05:13 2021
@author: Admin
"""
a = int(input('nhap a = '))
b = int(input('nhap b = '))
def uscln(a, b):
if (b == 0):
return a;
return uscln(b, a % b);
print('UCLN của',a,'và',b,'là:',uscln(a,b)) |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 19 10:15:08 2021
@author: Admin
"""
def selection_sort(nums):
# Giá trị này của tôi tương ứng với số lượng giá trị đã được sắp xếp
for i in range(len(nums)):
# Chúng tôi giả định rằng mục đầu tiên của phân đoạn chưa được sắp xếp là mục nhỏ nhất
... |
# Blessed [is] he that readeth, and they that hear the words of this prophecy,
# and keep those things which are written therein: for the time [is] at hand. (Revelation 1:3)
string_1 = "Camelot"
string_2 = "place"
print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)
"""
STRINGS & CONSOLE OUTPU... |
# Pilate wrote a title also, and put it on the cross. There was written, "JESUS OF NAZARETH, THE KING OF THE JEWS." (John 19:19)
def biggest_number(*args):
print max(args)
return max(args)
def smallest_number(*args):
print min(args)
return min(args)
def distance_from_zero(arg):
print abs(arg)
return... |
# If the world hates you, you know that it has hated me before it hated you. (John 15:18)
def tax(bill):
"""Adds 8% tax to a restaurant bill."""
bill *= 1.08
print "With tax: %f" % bill
return bill
def tip(bill):
"""Adds 15% tip to a restaurant bill."""
bill *= 1.15
print "With tip: %f" % bill
retu... |
# An example of the process of data analysis using Python 3
# Get Data, Prepare data, Analyze Data, Present Data.
#http://pandas.pydata.org/pandas-docs/version/0.20/10min.html
import pandas
import sys
from matplotlib import pyplot
from numpy import arange
# Plot Functions
def barplot(labels,data):
pos=arange(... |
lst = list()
while True:
msg = input('Say Something: ')
if msg == '/end':
break
else:
if msg.startswith(("how","what","why")):
lst.append(msg.title()+"?")
else:
lst.append(msg.title()+'.')
for i in lst:
print(i)
|
#Using String Formatting Here In This String
numbers=[4,5,6,7,8,]
string="Numbers are:{0}\t{1}\t{2}".format(numbers[2],numbers[3],numbers[4])
print(string)
#If We don't have the value with uss and we want to pass the value stratiaght to the print function
value="{x} {y} {z}".format(x="Anidh",y="Shubhu",z="Forever")
pri... |
def codingChallenge():
for x in range(1,6):
print('I am a programmer!')
codingChallenge()
def squaredValue():
print('Displaying The Squared Value from 1 to 9\n')
for x in range(1,10,1):
print(x**2)
squaredValue() |
product_Info={"TV":25000,"Radio":1200,"Laptop":53000,"Phone":80000,"Charger":800}
product=input("Enter The Product Name")
print(product_Info.get(product,"Item Not Found Try Again!")) |
odd_Numbers=[x for x in range(100) if x%2!=0]
print(odd_Numbers) |
student={"name":"Mark","student_id":15163}
all_students=[{"name":"Mark","student_id":15163},{"name":"Anidh","student_id":163}]
print(all_students[0]["name"]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.