text stringlengths 37 1.41M |
|---|
from random import choice
import time
# This functions are just the greetings just helps clean up the code.
def greetings_Lyra():
print()
print("Welcome, I'm Lyra! The best bot assistance you will ever meet. I will help you to take the best decision of your life.\nAfter this decision definetly your life will chang... |
# Escreva um programa em Python3 que receba um número real positivo e não nulo,
# calcule e imprima o resultado das seguintes operações aritméticas
# (n é o número recebido e e é o número de Euler):
# i) n²
# ii) n elevado à n-ésima
# iii) √n
# iv) ³√n
# v) e * n
# vi) π / n
# DICA 1: A única função que vocês precisa... |
# Complete o código do programa em Python3 que recebe dois valores quaisquer,
# armazenando-os nas variáveis v1 e v2, e em seguida troca os valores de v1 e
# v2 e imprime os valores trocados.
print("------------ TROCA DE VARIÁVEIS ------------")
v1 = input("Digite o valor da primeira variável: ")
v2 = input("Digite o... |
# Exercicio referente ao problema numero 1071 do URI ONLINE JUDGE.
# https://www.urionlinejudge.com.br/judge/pt/problems/view/1071
# Por: Renan Santana Desiderio
a = input() # recebe o valor de a
b = input() # recebe o valor de b
lista = [a,b] # transformei as duas variaveis em uma lista
lista.sort() # mand... |
# Exercicio referente ao problema numero 1099 do URI ONLINE JUDGE.
# https://www.urionlinejudge.com.br/judge/pt/problems/view/1099
# Por: Renan Santana Desiderio
c = input()
soma = 0
for i in range(c):
n = raw_input().split()
x = int(n[0])
y = int(n[1])
l = [x,y]
l.sort()
x = l[0]
y = l[1]
for s ... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class linkedList:
def __init__(self):
self.head = None
def printList(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
def push(self, new_data):... |
import random
from rpsls.classes import Characters, User, battle, gameoptions
choice1 = Characters(1, "Rock", "crushes", "crushes")
choice2 = Characters(2, "Paper", "covers", "disproves")
choice3 = Characters(3, "Lizard", "eats", "poisons")
choice4 = Characters(4, "Spock", "vaporizes", "smashes")
choice5 = Ch... |
# Check whether the given assertion holds for all elements of
# the given collection.
# - The given collection must be effective and the assertion
# must be a function involving a single argument and
# returning a boolean.
# - Returns true if and only if the given assertion is true
# for all the element... |
from SpecificationLibrary import *
# Compute the product of two sparse vectors.
def vector_product(left,right):
result = 0
for k in set(left.keys()) | set(right.keys()):
sum_k = left.get(k, 0) * right.get(k, 0)
if sum_k:
result += sum_k
return result
# Check whether the given v... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 21 17:20:01 2013
@author: Lars Vierbergen
"""
# Imports the file 'sortedList.py' and registers all its functions under
# the namespace `sortedList`
import sortedList
def merge(lst1, lst2):
"""Merges two sorted lists `lst1` and `lst2`
Returns a sorted list w... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 5 11:59:15 2013
@author: Lars Vierbergen
"""
from SpecificationLibrary import *
def rearrange(lst):
assert isinstance(lst, list)
assert (len(lst) % 2 == 0)
assert for_all(lst, lambda x: isinstance(x, int) and x !=0)
# Even veel jongens als meisjes
... |
t = ('a', 'b', 'c')
#t[0] = 'A'
t = ('A', 'b', 'c')
print(t)
'''
변수 = 값
name = "HI"
값 : 컴퓨터 memory 저장
1000 ('a','b','c')
2000 ('A', 'b', 'c')
5000 "HI"
stack(특수영역)
t 2000
name 5000
''' |
#1
my_list = ["A", "B", "C"]
for i in range(0,3):
print(my_list[i])
#2
print("A")
print("B")
print("C")
|
money = input('입력: ')
money = money.split()
if money[1] == '달러':
money[0] = int(money[0]) * 1167
elif money[1] == '엔':
money[0] = int(money[0]) * 1.096
elif money[1] == '유로':
money[0] = int(money[0]) * 1268
elif money[1] == '위안':
money[0] = int(money[0]) * 171
else:
print('잘못된 통화명을 입력하셨습니다.')
prin... |
data = [2, 4, 3, 1, 5, 10, 9]
data = sorted(data)
print(data)
'''
() : tuple - 빠르게 / 데이터 변동 X
[] : list - 순서O, 느려요
{} : dict - key값, 순서X, 값 커요 > 느려요
''' |
#1
char_list = ["A","B","C"]
for i in range (0,3):
print('출력:',char_list[i])
#2
print('출력:', "A")
print('출력:', "B")
print('출력:', "C") |
#format 메서드 활용
name1 = '김민수'
age1 = 10
name2 = '이철희'
age2 = 13
print('이름: {} 나이: {}'.format(name1,age1))
print('이름: {} 나이: {}'.format(name2,age2)) |
while True:
score = int(input('score:'))
if 0 <= score <= 100:
break
else: # 예외처리
print('Range exceeded!!!')
if 81 <= score <= 100:
score = 'A'
elif 61 <= score < 81:
score = 'B'
elif 41 <= score < 61:
score = 'C'
elif 21 <= score < 41:
score = 'D'
else:
score = 'E... |
#!/usr/bin/python
#divisors.py
'''
Find sum of divisors, for all N in a given list
'''
import time
def DoWork(nums):
sums = []
for n in nums:
divisors = [x for x in range(1,n+1) if not n % x]
#divisors.append(n)
sums.append(sum(divisors))
return sums
def DoWork_old(nums):
sum... |
# We pass the 'memoize' function the logic of our recursive procedure, in our example,
# the '__fib' procedure. We then define 'fib_memo' to be the return value from 'memoize(__fib)'.
# This indicates that the 'memoize' procedure must return another procedure! Lets consider the
# 'memoize' procedure further. This funct... |
#!/usr/bin/python
import random
def min(a):
min = None
for i in a:
if min is None:
min = i
else:
if i < min:
min = i
return min
if __name__ == "__main__":
a = [random.randint(0, 100) for i in range(0, 20)]
print(a)
print(min(a))
|
#!/usr/bin/python
class Graph:
m = None
def __init__(this):
this.m = {}
def addEdge(this, a, b):
if not a in this.m:
this.m[a] = set()
this.m[a].add(b)
def print(this):
print("\n".join([str(i[0]) + " -> " + ", ".join(str(j) for j in i[1]) for i in this.m.items()]))
class Queue:
he... |
#!/usr/bin/python
def isRotationOf(s1, s2):
"""Returns True if s1 is a rotation of s2"""
if len(s1) != len(s2):
return False
# Potential rotation match must have same first char.
for i in range(len(s1)):
print(i)
if s1[i] == s2[0]:
# Test for potential rotation...
il = None
resu... |
#!/usr/bin/python
def swap(ar, i, j):
print("swap [l={}, r={}]".format(ar[i], ar[j]))
temp = ar[i]
ar[i] = ar[j]
ar[j] = temp
def partition(ar):
"""Picks the last element of the array as a pivot.
Maintains two pointers, using each to traverse array from opposite directions as part
of ... |
#!/usr/bin/python
import math;
"""Checking primality of a number."""
def isPrimeDum(n):
"""non-optimized method.
Check every number between 2 and n - 1 and see if we can evenly divide into n.
Extremely inefficient."""
for i in range(2, n):
if n % i == 0:
return False
return True
def isPri... |
# - position argument
# - default argument
# - keyword
# def linear_search(l,key):
# for x in l:
# if key==x:
# return True
# else:
# return False
# l = [100,200,300,400,500]
# key = 400
# result = linear_search(l,key)
# print(result)
# 8 char
# 1 Upper
# 1 lower
# 1 special
# 5 digits
# ord
# chr
# ... |
# r read
# r+
# w write
# w+
# a append
# a+
# fp = open("input.txt","r")
# content = fp.read()
# print(content)
# print("-------------------------------------")
# content = fp.read()
# print(content)
# content = fp.read(25)
# print(content)
# readlines
# readline
# content = fp.readlines()
# print(content[:5])... |
# factorial(5) = 5 * factorial(4)
# 4 * factorial(3)
# 3 * factorial(2)
# 2 * factorial(1)
# 1
# def factorial(num):
# if num == 1:
# return 1
# else:
# return num * factorial(num-1)
# num1 = 400
# result = factorial(num1)
# print(result)
l = [100,200,300,400,500,6... |
prices = {
'banana': 4,
'apple': 2,
'orange': 1.5,
'pear': 3
}
stock = {
'banana': 4,
'apple': 5,
'orange': 6,
'pear': 7
}
for price in prices:
print(f'{price}')
print(f'Price: {prices[price]}')
print(f'Stock: {stock}')
total = 0
for price in prices:
inventory = prices[price] * stock[price]
... |
# Генераторы и итераторы представляют собой инструменты, которые часто используются
# для поточной обработки.
num_list = [1, 62, 7, 48, 15]
for i in num_list:
print(i)
print("\n")
itr = iter(num_list)
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr), "\n")
# print(next(itr)) # Ту... |
# Для открытия файла используется open()
f = open("Numberss.txt", "r")
print("file.closed: " + str(f.closed))
print("file.mode: " + str(f.mode))
print("file.name: " + str(f.name), "\n")
# Чтение данных из файла осуществляется методами read() и readline()
# print(f.read(), "\n")
# Можно указывать требуемое количество ... |
# Функция - это объект специального типа, поэтому её можно передавать другим
# функциям в качестве аргумента.
# Внутри функций можно создавать другие функции, вызывать их и возвращать как
# результат через return
# Функция как объект
# исходный список
a = [1,2,3,4,5]
# функция, возводящая переданное её число в квадрат... |
__author__ = 'User'
"""
Dear un-hebrew speakers:
'Tmura' is 'Grammatical modifier': an element that describes the object in sentence.
We love the name 'Tmura', So we use it.
for example:
without Tmura: Lummie and Arad study in Magshimim
with Tmura: Lummie and Arad study in Magshimim, The national cyber project
"""
f... |
import os
import imageio
import math
from points import Points, START_VALUE, MIDDLE_VALUE, END_VALUE
# calculate angle from angle between the two points three steps either way
ANGLE_POINTS_DELTA = 3
ANGLE_POINTS = ANGLE_POINTS_DELTA * 2 + 1
def follow_line(image, points, x, y):
print("Follow line, starting at "... |
# -*- coding: utf-8 -*-
import sqlite3 as sql
def create_and_update(list_currency):
con = sql.connect('currencies.db')
cur = con.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS currency (currency TEXT PRIMARY KEY, price REAL, time INTEGER);""")
for i in list_currency:
try:
cur... |
# -*- coding: utf-8 -*-
r"""
root = [3,9,20,null,null,15,7]
[[3],[9,20],[15,7]]
3
/ \
9 20
/ \
15 7
According to abrove, it is constructed in BFS order
"""
import collections
import math
import unittest
from typing import List, Optional, TypeVar, Generic
T = TypeVar("T")
class T... |
# Delete Middle Node: Implement an algorithm to delete a node in the middle (i.e., any node but
# the first and last node, not necessarily the exact middle) of a singly linked list, given only access to
# that node., the node is not the tail node
# EXAMPLE
# lnput:the node c from the linked list: a->b->c->d->e->f
# Res... |
# Return Kth to Last: Implement an algorithm to find the kth to last element of a singly linked list.
#
# Reference: leetcode: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
#
# Solutions 1: two pass, one pass count all, the calculated according to the length and n
# Solution 2: one pass, two cursors/p... |
# 5906. Number of Valid Words in a Sentence
# User Accepted:0
# User Tried:0
# Total Accepted:0
# Total Submissions:0
# Difficulty:Easy
# A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken d... |
# 4.8 First Common Ancestor: Design an algorithm and write code to find the first common ancestor
# of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not
# necessarily a binary search tree.
# Hints: #70, #76, #28, #36, #46, #70, #80, #96
#
# Keywords: LCA (lowest common an... |
"""
1175. Prime Arrangements
Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.)
(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)
Since the answer may be large, retu... |
"""
1155. Number of Dice Rolls With Target Sum
You have d dice, and each die has f faces numbered 1, 2, ..., f.
Return the number of possible ways (out of fd total ways) modulo 10^9 + 7 to roll the dice so the sum of the face up numbers equals target.
Example 1:
Input: d = 1, f = 6, target = 3
Output: 1
Explanat... |
# 2.8 Loop Detection: Given a circular linked list, implement an algorithm that returns the node at the
# beginning of the loop.
# Keywords: slow-fast pointers
# Solution: think like a long distance race, if a man runs faster, he can be 1 lap faster
# DEFINITION
# Circular linked list: A (corrupt) linked list in whi... |
# Partition: Write code to partition a linked list around a value x, such that all nodes less than x come
# before all nodes greater than or equal to x. If x is contained within the list, the values of x only need
# to be after the elements less than x (see below). The partition element x can appear anywhere in the
# "... |
from basketballPlayerPoly import BasketballPlayer
from volleyballPlayerPoly import VolleyballPlayer
def main():
print("Adding athletes")
athletes_list = []
choice = 0
while choice != 3:
choice = int(input("Enter 1 for basketball player, 2 for volleyball player, "
"3 ... |
from gcd import gcd
def multiInverse(base, number):
gcdAB = gcd(number, base)
if gcdAB != 1:
print("Inverse does not exist")
return -1
else:
i = 1
while True:
if (number * i) % base == 1:
return i
else:
i += 1 |
#2. Generate first N number of Fibonacci numbers. Take N value from user
i1=0
i2=1
x=int(input('enter upto to which fibonacci series should print'))
z=0
while z<=x:
print(i1)
nth=i1+i2
i1=i2
i2=nth
z=z+1
#3. Display multiplication table of K. Take k value from user
#Ex: 7 x 1 =7
#7 x ... |
import random
import cards
#Could be important if you need to ask questions
def ask_yes_no(question):
response = None
while response not in ("y","n"):
response = input(question).lower()
return response
#You will ask a number and it will return it. Will be useful to ask how many players you want.
d... |
# This multi-line string is called a ``docstring``.
#
# Docstrings document things --- in this case, it documents the purpose of the
# whole module.
#
# They have to be the first Python statement of the thing they document
# (excluding comments, like this explanation).
"""Utilities for reading different data files.
Al... |
class Room():
#Class variable
number_of_rooms = 0
#Constructor method for a class
#By using self, a method can invoke the object
#and access the attributes and methods of that object
def __init__(self, room_name):
self.name = room_name
self._description = None
self.linked_rooms = {}
... |
import sys
import os
def reverse(value):
return int(''.join(list(reversed(str(value)))))
if __name__ == '__main__':
first_line = sys.stdin.readline()
count = int(first_line)
results = []
for i in range(count):
a, b = map(int, sys.stdin.readline().strip().split())
c = reverse(a) +... |
# day 14
import math
QUANTITY = 0
NAME = 1
class Recipe:
def __init__(self, name, quantity, ingredients):
self.name = name
self.quantity = quantity
self.ingredients = ingredients # list of tuples with quantity, material name
def print_cookbook(big_list):
for material in big_list:
print('to make', big_list... |
#day 7
def computePart1(luggages, containers):
bags = set()
while len(containers) > 0:
aux = []
for bag in luggages:
for p in containers:
if p in luggages[bag]:
aux.append(bag)
containers = set(aux)
bags.update(containers)
return len(bags)
def computePart2(luggages, bag):
if luggages[ba... |
#day 19
# run with python3
import regex
from itertools import count
def parseRules(rules):
rules = rules.splitlines()
rulesDictionary = {}
for rule in rules:
number, values = rule.split(': ')
rulesDictionary[number] = values
return rulesDictionary
def build_regex(ruleKey, pa... |
print('this is my greeting')
def sum(num1,num2):
result = (num1 + num2)
return (result)
print("updated info")
|
#Stringlere Yakından Bakalım
print(type(123))
print(type('123'))
''' string ifadeleri kullanırken
kesme işareti kullanmak daha doğrudur.'''
print('a' + 'b')
print('a''b')
print('a' * 3)
#String Methods
#len()
'''içerisine girmiş olduğumuz
ifadenin uzunluğunu geri döndürür'''
my_name = 'irem_sena_celik'
print... |
import math
print('3. Volume of sphere')
diameter = int(input('Enter diameter of the sphere: '))
rad = diameter / 2
v = (4/3) * math.pi * (rad ** 3)
print('The volume of sphere is: ' + str(v)) |
def MapListOfWords(StringList):
if type(StringList) != list:
print('Input parameter must be a list')
return
resultList = []
for s in StringList:
resultList.append(len(s))
return resultList
stringlist = ['Bangalore', 'Hyderabad', 'Mumbai', 'Pune', 'Patna']
print(type(stringlis... |
i = 1
print(10-i)
i = "meow"
print(i)
i = True
print(i)
i = ["meow", 1, True]
print(i)
i = {"cat": 1, "meow": 2, True: False}
print(i)
print(i["cat"])
print(i[True])
i = (3, 5)
print(i)
print(i[1], i[0])
class Cat(object):
def __init__(self, name):
self.name = name
def voice(self):
print("... |
"""
Given the root of a binary search tree, rearrange the tree in in-order so that the
leftmost node in the tree is now the root of the tree, and every node has no left child
and only one right child.
"""
def increasingBST(root):
def inorder(node):
if node:
inorder(node.left)
nod... |
###Ackermann Function
def mn(m,n):
if m==0:
return n+1
else:
if m>0 and n==0:
mn(m-1,1)
elif m>0 and n>0 :
mn(m-1,mn(m,n-1))
|
# Import graph class
from graph_search.graph_utility import create_graph_from_txt_file, Graph
# assumptions
# take in a graph with all nodes connected in some way
# each edge cost is distinct
g = Graph()
g.add_vertex(0)
g.add_vertex(1)
g.add_vertex(2)
g.add_vertex(3)
g.add_edge(0, 1, 1)
g.add_edge(1, 2, 4)
g.add_e... |
import re
def operation(a, b, operator):
if operator == '+':
return a + b
elif operator == '-':
return a - b
elif operator == '*':
return a * b
else:
try:
return a / b
except:
return "Error"
def priority(operator, operators, numbers):
... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
import statsmodels.formula.api as smf
from models.linear import LinearRegression
def print_results(fitted_model, y_test, y_pred):
p... |
from typing import Optional, Union
import warnings
import numpy as np
from ._math import check_invertible_array, normal_eq
from ..utils import check_is_fitted
class LinearRegression:
"""
The Linear Regression implementation using NumPy.
The Linear Regression model try to fit a linear model with weights... |
import numpy as np
array = np.array([[1, 2, 3],
[2, 3, 4]])
print(array)
print('number of dim: ', array.ndim)#几维矩阵
print('shape: ', array.shape)#几行几列
print('size: ', array.size)#总元素个数
print("############################")
a0 = np.array([1, 1, 1])
print(a0)
print(a0.shape)
print(a0.ndim)
a1 = np.arra... |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x + i/10))#10变大动画变慢
return line,
def init():
line.set_ydata(np.sin(x))
return line,
#frame... |
append_text = "\nThis is appended file."
my_file = open('myfile.txt', 'a')
my_file.write(append_text)
my_file.close()
print(append_text) |
#coding=utf-8
import multiprocessing as mp
def job(x):
return x*x
def multicore():
pool = mp.Pool() #定义Pool,也可以自行分配几个进程(如pool=mp.Pool(2)分配成两个核
res = pool.map(job, range(10))#用map()获取结果,在map()中需要放入函数和需要迭代运算的值,然后会自
print(res)#行分配给cpu核,返回结果
if __name__ == '__main__':
multicore()
#进程池Pool,进程池是将我们所... |
import numpy as np
A = np.arange(3, 15)
print(A)
print(A[3])#输出一维向量A下标3的对应值
a = np.arange(3, 15).reshape((3, 4))
print(a)
print(a[2][2])#输出矩阵A下标[2][2]的对应值
print(a[2, 2])#输出矩阵A下标[2][2]的对应值
print(a[:, 1])#输出矩阵A第一列所有元素
print(a[1, 1:3])#输出矩阵A第一行的一到三列的元素(即第一列和第二列)
print('#################\n')
for row in a:#逐行输出矩阵a
prin... |
"""Demonstration of the Template design pattern. Category: behavioral.
The template pattern defines an abstract base class that defines an
algorithm's skeleton but defers some of the implementations to
subclasses.
A template can consist of abstract methods, concrete methods (if several
subclasses will want the same b... |
class Hi:
def sayHi(self):
print("Hello, World!")
# assign class to variable.
sayhi = Hi()
# call function sayHi utilizing class
sayhi.sayHi()
|
#!/usr/bin/python3
"""find the peak element on a list"""
def find_peak(list_of_integers):
"""find_peak func
Args:
list_of_integers: unsorted list to sheck
"""
if not list_of_integers:
return None
l = list_of_integers
lenth = len(list_of_integers)
for e in range(lenth - 1):
... |
### Q:You are given as input an unsorted array of n distinct numbers, where n is a power of 2.
### Give an algorithm that identifies the second-largest number in the array, and that uses at most
### n +log_2 n-2 comparisions
### Idea: use binary max-heap to solve this problem
def buildheap(arr):
### Input:... |
#!/usr/bin/python3
def add_tuple(tuple_a=(), tuple_b=()):
if tuple_a is None or tuple_a is not None:
if len(tuple_a) == 0:
atup = (0, 0)
elif len(tuple_a) == 1:
atup = (tuple_a[0], 0)
else:
atup = (tuple_a[0], tuple_a[1])
if tuple_b is None or tupl... |
#!/usr/bin/python3
""" Script that lists cities from specified database"""
import MySQLdb
from sys import argv
if __name__ == "__main__":
db = MySQLdb.connect(user=argv[1], passwd=argv[2], db=argv[3])
cursor = db.cursor()
cursor.execute("""SELECT cities.name FROM cities JOIN states ON\
ci... |
#!/usr/bin/python3
"""Create a square class"""
class Square:
"""Create a square object"""
def __init__(self, size=None):
"""Use __init__ to initialize square with private size.
Args:
size (int): Private size of square.
"""
self.__size = size
|
#!/usr/bin/python3
"""Function to add two integers"""
def add_integer(a, b=98):
"""Returns the sum of two integers.
Accepts float as well, but must be converted to int.
Args:
a (int/float): first argument
b (int/float): second argument
Return:
Sum of a + b
Raises:
... |
#!/usr/bin/python3
for x in range(0, 10):
for y in range(1, 10):
if (y - x) <= 0:
continue
elif y == 9 and x == 8:
print("{:d}{:d}".format(x, y))
break
else:
print("{:d}{:d}".format(x, y), end=", ")
|
def run ():
objetivo = int(input("ingrese numero: "))
epsilon = 0.000000000001
alto = objetivo
bajo = 0.0
respuesta = (bajo + alto)/2
if objetivo <= 0:
print("los numeros negativos no tienen raices reales")
else:
while abs(respuesta**2 - objetivo) >= epsilon:
... |
class Figura:
def __init__(self, base, altura):
self.base =base
self.altura = altura
def area (self):
return self.base*self.altura
class Cuadrado(Figura):
def __init__(self, base):
super().__init__(base, base)
class Rectangulo (Figura):
def __init__(self, base, ... |
# This program extracts the csv lines from ExpensesOK iOS application and converts it into a Excel friendly copy
# pastable format.
# ExpensesOK does not provide support for income, so this app separates an 'income' and 'expenses' category for you.
import csv, os, re, datetime
#### EDIT VARIABLES BELOW AND PROGRAM SH... |
#!/usr/bin/env python
def checkrightangletri(x, y, z):
if x > y and x > z:
if (x ** 2) == ((y ** 2) + (z ** 2)):
print("Yes, this is right angle triangle")
else:
print("No, this is not right angle triangle")
elif y > x and y > z:
if (y ** 2) == ((x ** 2) + (z... |
#!/usr/bin/env python
def primenums(x):
prime = []
for num in range(0, x):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
prime.append(num)
print(prime)
if __name__ == "__main__":
one = input... |
"""lib.bitwarden
This module contains all of the magic that the Bitwarden algorithms use. This
will be used to test behaviors as well as create new ciphers.
"""
import base64
from Crypto import Hash, Random
from Crypto.Cipher import AES
from Crypto.Util import Padding
from Crypto.Protocol import KDF
from .cipherstrin... |
## importing all required libraries
from bs4 import BeautifulSoup
import requests
import csv
pages = 5 ## total number of pager
current = 1 ## start page index
dataset = [] ## empty list to store scrapped data
## loop to scrape data from all 5 pages
while current <= pages:
url = "http://econpy.pythonanywhere.com/e... |
def peek(word_list):
if word_list:
word = word_list[0]
return word[0]
else:
return None
def match(word_list, expecting):
if word_list:
word = word_list.pop()
if word[0] == expecting:
return word
else:
return None
else:
return None
def skip(word_list, word_type):
while peek(word_list) == wor... |
# create a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
# create a basic set of states and some cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
# add some more cities
cities['NY']... |
g=int(input())
temp=g
rev=0
while temp!=0:
rev=(rev*10 )+ (temp%10)
temp=temp//10
if g==rev:
print"is a palindrome"
else:
print"is not a palindrome"
|
import sqlite3
Database = '/Users/noahg/Desktop/Neuer Ordner/HS_Database.db'
connection = sqlite3.connect(Database)
cursor = connection.cursor()
#command = '''create table Accounts (Name string, Passwort string, Level int, Gold int, Packs int, Staub int, Ep int, Epnextlevel int);'''
command = '''select * from Accoun... |
n1 = 4
n2 = 2
###addition of two numbers
N = n1+n2
print(N)
###subtraction of two numbers
sub = n1-n2
print(sub)
###dicison of two numbers
div = n1/n2
print(div)
##modular of two numbers
mod = n1%n2
print(mod)
####exponential of two numbers
exp = n1**n2
print(exp) |
A=float(input())
B=float(input())
MEDIA=(3.5*A+7.5*B)/11
print("MEDIA =",'{:.5f}'.format(MEDIA)) |
# find Pythagorean triplet
def is_pythagorean_num(a, b, c):
return ((a ** 2 + b ** 2) == c ** 2)
def find_pythagorean_by_count(count):
a = 0
while True:
if a > count:
break
a += 1
for b in range(a + 1, count):
for c in range(b + 1, count):
... |
# this program is used to clear head space and end space in a string
def clear_head_space(line):
index = 0
for i, ch in enumerate(line):
if ch != " ":
index = i
break
return line[index:]
def clear_tail_space(line):
index = 0
for i, ch in enumerate(line[::-1]):
... |
#this program use to find the number can divide a range of number
# this is ugly ways to solve this problem
def find_num_div_range(start, end):
small_num = start
while True:
is_find = True
for i in range(start, end + 1):
if small_num % i != 0:
is_find = False
... |
# use this program to verify the month
import re
re_str = r".+(Jan|Feb|Mar|Jan|Jul|Apr|Sep|Oct|Nov)"
f = open("data.txt", 'r')
for line in f:
print re.match(re_str, line).groups()[0]
f.close()
|
# this program is used for manage user login info
import crypt, string
class User:
def __init__(self, name, pwd):
self._name = name
self._pwd = crypt.crypt(pwd, "666")
def can_login(self, name, pwd):
pwd = crypt.crypt(pwd, "666")
if name != self._name or pwd != self._pwd:
... |
# this program is used to get max value in the list
import random
def max2(a, b):
if a > b:
return a
else:
return b
def min2(a, b):
if a < b:
return a
else:
return b
def max_list(l):
count = len(l) - 1
if count < 0:
return None
m = l[0]
for ... |
"""
https://leetcode.com/problems/find-lucky-integer-in-an-array/
Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value.
Return a lucky integer in the array. If there are multiple lucky integers return the largest of them. If there is no lucky integer retu... |
def merge_sort(A):
if len(A)>1:
q=int(len(A)/2)
Left=A[:q]
right=A[q:]
merge_sort(Left)
merge_sort(right)
i=j=k=0
while i<len(Left) and j<len(right):
if Left[i]<right[j]:
A[k]=Left[i]
i+=1
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.