text stringlengths 37 1.41M |
|---|
import random
import string
user = input('please enter the length of the password: ')
num = int(user)
def specific_string(length):
sample_string = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#%^*-=[]"
result = ''.join((random.choice(sample_string)) for x in range(length))
print(... |
#CTI-110
#P4HW1 - Distance Traveled
#Roger Thompson
#62818
# Ask user two questions: The speed of a vehicle,and number of hours it has traveled.
# Display the distance that the vehicle has traveled for each hour of that time period.
def main():
choice = 'y'
while choice =='y':
#get # to ... |
'''
This module handles the game strategy (only) of a player.
'''
import random
import const
from game_board import GameBoardADT
from chain_finder import ChainFinder
from placer import Placer
# Enter your own player name
playerName = "Robin Stephenson"
# The game board
board = GameBoardADT()
finde... |
#code for the bot
import tweepy, time, sys, os
from dotenv import load_dotenv
load_dotenv()
#these are where the API Tokens that Morgan set up will go, when the applicaton is approved
CONSUMER_KEY = os.getenv('CONSUMER_KEY')
CONSUMER_SECRET = os.getenv('CONSUMER_SECRET')
ACCESS_KEY = os.getenv('ACCESS_KEY')
ACCESS_SE... |
import math as mt
#Algorithm to find teh Co Factors of a Number
def findCoFactors(num):
#Return if the numbers is 0 or 1
if num == 0 or num == 1:
return
#Return if the numbers is not even
if num % 2 != 0:
return
upperBound = mt.ceil(mt.sqrt(num))
lowerBoun... |
def lcm(hnum):
num = 1
while(True):
rem = 0
for n in range(2,hnum+1):
if (num % n == 0) and hnum:
rem += 1
if rem == (hnum-1):
break
num += 1
return num
print lcm(20) |
# JSON is commonly used with data APIS. Here how we can parse JSON into a Python dictionary
import json
userJSON = '{"firstname": "John", "lastname": "Doe", "age": 30}'
user = json.loads(userJSON)
print(user)
print(user['firstname'])
car = {'make': 'Ford', 'model': 'Mustang', 'year': 1970}
carJson = json.dumps(car... |
def countdown():
i = 5
while i > 0:
yield i
i -= 1
for i in countdown():
print(i)
def countdown(i):
while i > 0:
yield i
i -= 1
for i in countdown(i):
print(list(countdown(5)))
for i in countdown(5):
print(list(countdown(5)))
for i i... |
#in space_age file create SpaceAge function
class SpaceAge:
def __init__(self, seconds):
self.seconds = seconds
# COACHES' NOTE: don't forget to clean up 'pass'
pass
def seconds_to_years(self):
return self.seconds / (60 * 60 * 24 * 365.25) # Calculate seconds to years
def... |
def reciprocate():
global num, den
temp = num
num = den
den = temp
def add(n):
global num, den
num += n*den
def sum(n):
string = str(n)
addition = 0
for i in xrange(len(string)):
addition+=int(string[i])
return addition
limit = 100
if limit == 1:
num = 2
elif limit%3 != 0:
num = 1
else:
num = 2*(li... |
def is_same_multiple(number):
string = list(str(number))
string.sort()
for i in xrange(2,7):
newnumber = number*i
newstring = list(str(newnumber))
newstring.sort()
if string != newstring:
return False
return True
# print is_same_multiple(125874)
for i in xrange(1,1000000):
if is_same_multiple(i):
pr... |
def is_divisible(number):
primelist=[2,3,5,7,11,13,17]
string = str(number)
for i in xrange(1,8):
substring = string[i:(i+3)]
if int(substring)%primelist[i-1] != 0:
return False
return True
def is_pandigital(number):
if list(set(number)).__len__() == 10:
return True
return False
numberlist = []
# prin... |
def is_prime(n):
i = 2
factors = []
while (i * i <= n):
if (n % i == 0):
return False
i = i + 1
return True
result = 0
for i in xrange (0,10):
if (i%1000 == 0):
print i
if is_prime(i):
result += i
print result |
#liner serch in sorted array :
def findElement(array,item):
n = len(array)
for i in range(n):
if item == array[i]:
print ('present')
elif item < array[i]:
return -1
return
array = [1,2,3,43,25,44,36,90,5,6,39,40,5,7,4,35,823,46,12,48,2... |
# Given a string, find the first non-repeating character in it and return its index.
# If it doesn't exist, return -1. # Note: all the input strings are already lowercase.
#Brute force way of doing it
def first_unique_char(string):
for index,i in enumerate(string):
# bcs function is looping through chars chronol... |
# Given an array of integers, determine whether the array is monotonic or not.
A = [6, 5, 4, 4]
B = [1,1,1,3,3,4,3,2,4,2]
C = [1,1,2,3,7]
def monotonic_array(array):
return all(array[i] <= array[i+1] for i in range(len(array) - 1)) or \
all(array[i] >= array[i+1] for i in range(len(array) -1))
print... |
class Base:
def __init__(self):
print("Base")
class Derived(Base):
pass
if __name__ == '__main__':
d = Derived() # 자녀 클래스가 별도 생성자를 생성하지 않으면 default로 생성자를 만들어준다.
# def __init__(self):
# super.__init__(self)
|
# @decorator
class MyDecorator:
def __init__(self, f): # __init__() 메서드의 매개변수를 통해서 함수를 받아들이고 데이터 속성에 저장해 둠
print("Initializing MyDecorator...")
self.func = f # MyDecorator의 func 데이터 속성이 print_hello를 받아둠.
def __call__(self):
print("Begin:{0}".format(self.func.__name__))
self.fu... |
class A:
pass
class B:
pass
class C:
pass
class D(A,B,C): # 다중 상속
pass
#########################################################################
# 다중 상속시 주의 사항 - 죽음의 다이아몬드
class K:
def method(self):
print("K")
class L(K):
def method(self):
print("L")
class M(K):
def met... |
class Car: # 자료형 선언
def __init__(self): # 생성자 : 함수로 정의 / (self) 필수 - java의 this 와 동일 - 생략 불가
self.color = 0xFF0000 # 차량색상(헥사 코드(Red)) / self.변수 = x : 필드 선언
self.wheel_size = 16 # 바퀴크기 --
self.displacement = 2000 # 엔진 배기량
# 값이 고정되어 범용성이 떨어진다.
def forward(self): # 전진 ... |
import subprocess
board=["-","-","-",
"-","-","-",
"-","-","-"]
def display_board():
print(board[0] + " | " + board[1] + " | " + board[2])
print('--+---+--')
print(board[3] + " | " + board[4] + " | " + board[5])
print('--+---+--')
print(board[6] + " | " + board[7] + " | ... |
import random
import math
import string
class Board(object):
def __init__(self, num_letters):
self.num_letters = num_letters
self.letters = self.get_board_letters()
self.row_size = int(math.sqrt(self.num_letters))
def get_board_letters(self):
board_letters = []
vowels ... |
from cs50 import get_float
while True:
c = get_float ("Change owed: ")
if c < 0:
get_float ("Change owed: ")
else:
break
counter = 0
cents = round(int(c * 100))
while cents > 24:
cents -= 25
counter+=1
if cents < 25:
break
while cents > 9:
cents -= 10
counter +=... |
# L-system for algae growth using G(n) = G(n-1)G(n-2) concatenation algorithm
def algae(n):
if n == 0:
print('A', end="")
elif n == 1:
print('AB', end="")
else:
algae(n-1)
algae(n-2)
iterations = 8 # how many rounds of substitutions to make
for i in range(iterations):
p... |
import threading
import time
flag = 0
class myThread (threading.Thread):
def __init__(self, threadId, name, counter):
threading.Thread.__init__(self)
self.threadId = threadId
self.name = name
self.counter = counter
def run(self):
print(f"starting {self.name} \n")
... |
class RecException(Exception):
def __init__(self, msg):
super().__init__(msg)
class Recurso:
def __init__(self, name = None, size = 0):
self.__name = name
self.__size = size
@property
def name(self):
return self.__name
@property
def size(self):
return... |
from tkinter import *
def converter():
gram_results = float(two_label.get()) * 1000
pound_results = float(two_label.get()) * 2.20462
ounce_results = float(two_label.get()) * 35.247
gram_text.delete("1.0", END)
gram_text.insert(END, gram_results)
pound_text.delete("1.0", END)
... |
def katiesort(books):
empty = []
alpha = 'abcdefghijklmnopqrstuvwxyz'
for a in alpha:
for b in books:
if b[0].lower() == a:
empty.append(b)
books.remove(b)
return empty
print(katiesort(['beer', 'galaxy', 'red', 'clear', 'science', 'math']))
|
#Lab 1b Task 1: Mean of a list
# Write your calculate_mean function here.
def calculate_mean(ar):
m=sum(ar)/len(ar)
return m
# You can use this to test your function.
# Any code inside this `if` statement will be ignored by the automarker.
if __name__ == '__main__':
# Run your `calculate_mean` function with e... |
#!/usr/bin/env python
"""main.py: A mini Boggle game implementation."""
import string
from board import Board
from game import Game
MIN_NUMBER_OF_PLAYERS = 2
class ConsoleUI(object):
def get_number_of_players(self):
"""
Reads number of players in the game from the console and returns it.
... |
#Exercise 4
#import numpy package
import numpy as np
#txt file into numpy array
data = np.loadtxt("precip_data.txt", skiprows=1, usecols=2)
prec_min = data.min()
print("The minimum precipitation is " + str(prec_min))
prec_max = data.max()
print("The maximum precipitation is " + str(prec_max))
prec_me... |
from random import shuffle
a1 = input('Digite o nome do 1º aluno: ')
a2 = input('Digite o nome do 2º aluno: ')
a3 = input('Digite o nome do 3º aluno: ')
a4 = input('Digite o nome do 4º aluno: ')
ordem = [a1, a2, a3, a4]
shuffle(ordem)
print('A ordem de apresentação é:\n{}'.format(ordem))
|
user = 0
n1 = int(input('\nDigite o 1º valor: '))
n2 = int(input('Digite o 2º valor: '))
while user != 5:
user = int(input('''
Escolha uma opção:
[ 1 ] - Somar
[ 2 ] - Multiplicar
[ 3 ] - Maior
[ 4 ] - Novos Números
[ 5 ] - Sair do programa
'''))
if user == 1:
print('\n{} + {} = {}'.format(n1, n2, n1 ... |
velo = float(input('\n\033[1;34mA quantos Km/h seu carro está rodando?\033[m\n'))
if velo > 80:
multa = float((velo - 80) * 7)
print('\n\033[4;31mVocê foi multado!\033[0;31m A multa é de \033[1;33mR${:.2f}\033[m'.format(multa))
else:
print('\n\033[4;32mVocê está dentro do limite de velocidade!\033[0;32m Se... |
n = int(input('Digite um número inteiro: '))
print('O antecessor de {} é {}'.format(n,n-1))
print('O sucessor de {} é {}'.format(n,n+1))
|
val = float(input('\n\033[35mQual o preço da casa? R$'))
sal = float(input('\n\033[35mQual o seu salário atual? R$'))
anos = float(input('\n\033[35mEm quantos anos vai pagar?'))
parcelas = val / (anos * 12)
print('\n\033[36mTodo mês você terá que pagar \033[4;33mR${:.2f}\033[0;36m para pagar a casa!'.format(parcelas)... |
lista = []
par = []
imp = []
while True:
lista.append(int(input('Digite um valor: ')))
while True:
continuar = str(input('Continuar? [S/N]: ')).strip().upper()[0]
if continuar in 'SN':
break
else:
print('Valor inválido')
if 'N' in continuar:
break
fo... |
lista = input('Digite uma expressão com parênteses: ')
if lista.count('(') == lista.count(')'):
print('\033[32mExpressão aceita\033[m')
else:
print('\n\033[31mExpressão incorreta!\033[m')
|
from random import randint
com = randint(0, 10)
tent = 0
user = 0
while com != user:
user = int(input('\nAdvinhe o número (0 até 10): '))
tent += 1
if user > com:
print('Valor alto!')
elif user < com:
print('Valor baixo!')
print('''
Parabéns! Você Advinhou!
Comp = {}
Você = {}
Tentati... |
from time import sleep
from random import randint
jogadas = []
jog = []
print('-'*45)
print(f'{"JOGA NA MEGA SENA":^45}')
print('-'*45)
qnt = int(input('Quantos jogos você quer que eu sorteie? '))
print(f'{f" SORTEANDO {qnt} JOGOS ":=^45}')
for n in range(0, qnt):
cont = 0
while True:
tent = randint(1,... |
lista = [[], []]
for v in range(0, 6):
n = int(input(f'Digite o {v+1}º valor: '))
if n % 2 == 0:
lista[0].append(n)
else:
lista[1].append(n)
print(f'''
Os valores PARES digitados foram: {lista[0]}
Os valores ÍMPARES digirados foram: {lista[1]}
''')
|
#IMC = 80 kg ÷ (1,80 m × 1,80 m) = 24,69 kg/m2 (Peso ideal)
peso = float(input('Qual o seu peso? '))
altura = float(input('Qual sua altura? '))
imc = peso / (altura ** 2)
if imc < 18.5:
print('Você está \033[33mABAIXO DO PESO!\033[m')
elif imc >= 18.5 and imc < 25:
print('Você está \033[32mNO PESO IDEIAL!\0... |
#!/usr/bin/env python27
#Importing the modules
from BeautifulSoup import BeautifulSoup
import sys
import urllib2
import re
import json
#Ask for movie title
title = raw_input("Please enter a movie title: ")
#Ask for which year
year = raw_input("which year? ")
#Search for spaces in the title string... |
#
# os01a.py
# Bernard Sypniewski
# This file demonstrates some ways that we can use the os module
# to manipulate the operating system. Since PYTHON is cross-
# platform, some of the results here will differ on different
# operating systems like the MAC OS or LINUX.
#
import os
print "This script demonstrat... |
print "Simple for loop using a range variable"
print
for x in range(10):
print "Burp!"
print
print "Counting by 5s"
for x in range(0,10,5):
print str(x) + " Errruppppp!"
print
print "The White Knight (from Alice in Wonderland) counts backwards:"
for x in range (10, 0, -1):
print str... |
f = input("Enter a file ")
fd = open(f, "r")
list = list()
for line in fd:
for buf in line.rstrip().split():
if buf in list: continue
list.append(buf)
list.sort()
print(list)
|
import random as rand
import pygame
# 0 = empty, 2 = player head, 1 = player body, 3 = food
def init_board() :
global snake
global direction
global food
global squarespace
for i in range(squarespace):
row = []
for j in range(squarespace):
row.append(0)
gameboard.... |
import random
print('Hello, this is Rock, Paper & Scissors for you!')
namep1 = input('Whats your name? \n')
print("Hello", namep1, "!")
again_ = 1
while again_ == 1:
player1error = 1
tie_dummy = 0
print(r"For Rock enter - '1'")
print(r"For Scissors enter - '2'")
print(r"For Paper ent... |
def check_start_end_time(start, end, total_duration):
'''
start and end can be of any units. Just make sure that the units for
start, end and duration are consistent
'''
# 1. populate start
if start is None:
start = 0
# 2. confirm the end secs
if end is None:
end = tot... |
# Create an application that returns 'fizz' when a number is divisible by 3
# returns 'buzz' when a number is divisible by 5
# returns 'fizz_buzz' when a number is divisible by both 3 and 5
number = {'one':1,'two': 2,'three': 3,'five': 5,'twelve': 12,'fifteen': 15}
def fizzbuzz(numbers):
for key ,value in number... |
import sqlite3
class sqlite3_base():
base = sqlite3
cursor = None
def __init__(self):
self.base = sqlite3.connect('baseprueba3.db')
print("Base creada")
self.cursor = self.base.cursor()
try:
self.cursor.execute("CREATE TABLE producto(id integer PRIMA... |
"""Convenient column selectors.
## Rationale
Column selectors are convenience functions for selecting columns that share some property.
## Discussion
For example, a common task is to be able to select all numeric columns for a
subsequent computation.
Without selectors this becomes quite verbose and tedious to writ... |
# -----------------------------------------------------------------------------
# Distributed Systems (TDDD25)
# -----------------------------------------------------------------------------
# Author: Sergiu Rafiliu (sergiu.rafiliu@liu.se)
# Modified: 24 July 2013
#
# Copyright 2012 Linkoping University
# -------------... |
'''
Created on Dec 13, 2020
@author: Lawrence
'''
from blackhole import Black_Hole
from prey import Prey
#Special will boost the speed of any prey that goes in it but not for Hunters
#The speed will keep increasing if the prey goes into another Special simulton
class Special(Black_Hole):
def __init... |
# -*- coding: utf-8 -*-
'''
Задание 4.8
Преобразовать IP-адрес в двоичный формат и вывести вывод столбцами, таким образом:
- первой строкой должны идти десятичные значения байтов
- второй строкой двоичные значения
Вывод должен быть упорядочен также, как в примере:
- столбцами
- ширина столбца 10 символов
Пример выво... |
def assert_is_none(name, value):
"""A convenience function for reporting on values that should be None.
Raises a ValueError."""
if value is not None:
template = '{0} should be None, not {1}'
raise ValueError(template.format(name, value))
def assert_bounded(name, lower, upper, value):
"... |
import requests
url_ddg = "https://api.duckduckgo.com"
test_input = ["Washington",
"Adams",
"Jefferson",
"Madison",
"Monroe",
"Jackson",
"Van Buren",
"Harrison",
"Tyler",
"Polk",
... |
Width = raw_input('Width of box ==> ')
print Width
Height = raw_input('Height of box ==> ')
print Height
Character = raw_input('Enter frame character ==> ')
print Character
print '\nBox:'
print Character * int(Width) + '\n', Character, Width + 'x' + Height + ' ' * (int(Width)-(len(Width)+len(Height)+5)),... |
"""
Recursion: a lesson in meeseeks
"""
def blast(n):
if n <= 0: ##basis step
print "Blast off!"
else: ##recursive step
print n
blast(n-1)
print n
def factorial(n):
if n==1:
return 1
else:
x = factorial(n-1)
return x*n
... |
"""
Program used to determine populations of foxes and bunnies
"""
## define functions for both populations
def bpop_next(bpop, fpop):
bpop_next = (10*bpop)/(1+0.1*bpop) - 0.05*bpop*fpop
bpop_next = int(bpop_next)
return bpop_next
def fpop_next(bpop, fpop):
fpop_next = 0.4 * fpop + 0.02... |
import lab05_util
def print_info(restaurant):
restaurant[3] = restaurant[3].split('+')
print restaurant[0], "(%s)" %(restaurant[5])
print "\t" + restaurant[3][0]
print "\t" + restaurant[3][1]
if len(restaurant[6])>=3:
newsum = sum(restaurant[6]) - min(restaurant[6]) - max(rest... |
"""
Author: John Rivera riverj5@rpi.edu
Purpose: This program shows the user a list of legos. The user then asks for a type of lego, and the program shows a combination that could be used to make that lego. If it's not possible with the given lists of legos, the program will let the user know
"""
import... |
'''
This is code to test your functions in this lab. It is driven by a
Python module called nose, which has been imported here.
We assume your program is called lab10.py, and we import all the
function in your program here. Make sure any other code in lab10.py
is under the
if __name__ == "__main__":
line.
... |
"""
Author: John Rivera
Purpose: Moves a "turtle" in coordinate space using user inputs.
"""
def move(x,y,direction,amount):
if direction == 'right':
if amount == 'move':
x += 20
elif amount == 'jump':
x += 50
else:
x += 0
elif dire... |
# stack the ( bracket indexes until a ) bracket is found
# slice the expression with the last index and current one
expression = '1 + (2 - (2 + 3) * 4 / (3 + 1)) * 5'
s = []
for i in range(len(expression)):
ch = expression[i]
if ch == '(':
s.append(i)
elif ch == ')':
print(expression[s.pop()... |
n = int(input())
sum_names = 0
set_odd = set()
set_even = set()
for i in range(1, n + 1):
name = input()
for ch in name:
sum_names += ord(ch)
sum_names = sum_names // i
if sum_names % 2 == 0:
set_even.add(sum_names)
else:
set_odd.add(sum_names)
sum_names = 0
... |
# def get_magic_triangle(n):
# triangle = [[1], [1, 1]]
# if n == 1:
# return [[1]]
# elif n == 2:
# return triangle
# else:
# for i in range(2, n):
# triangle.append([
# triangle[i - 1][j - 1] + triangle[i - 1][j]
# if 0 <= j - 1 and j... |
from collections import deque
# recieve integers stack and deque
chocolate = [int(ele) for ele in input().split(', ')]
milk = deque([int(ele) for ele in input().split(', ')])
milkshakes = 0
while chocolate and milk:
# invalid chocolate case
if chocolate[-1] <= 0 and milk[0] <= 0:
chocolate.pop()
... |
# from itertools import permutations
#
# line = input()
# result = list(permutations(list(line)))
# for ele in result:
# print(''.join(ele))
from collections import deque
def permutation(chars, count=0):
if count == len(chars):
print(''.join(chars), end=' ')
return
for i in range(count, le... |
# a module is a file with python code
# stored in packages they contain different functionality that can be imported in other code
# builtin modules math,os,sys,itertools,random,functools
import math as m
# needs to be called every time with the function
print(m.trunc(4.5))
# python reads code from top to bottom so t... |
# fixed typeError by casting to int
numbers_list = list(map(int, input().split(", ")))
result = 0
# fixed typeerror by iterating trough elements
for number in numbers_list:
# number = numbers_list[i + 1]
# changed condition logic to fix proper results
if number <= 5:
result *= number
elif numbe... |
# comprehension is a short way to code a sequence
nums = [ele for ele in range(6)]
# comprehension must be used for simple operations to make it readable
# there are 4 types of comprehension list,dictionary,set and generator
# they require les memory, shorter syntax, easier data manipulation
# filtering numbers
x = [1,... |
word = input()
print(''.join([ch for ch in word if ch not in 'aouei']))
|
import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as spi
def f(x):
return np.sin(x) * 0.5 * x
x = np.linspace(-2 * np.pi, 2 * np.pi, 25)
ipo = spi.splrep(x, f(x), k=1)
iy = spi.splev(x, ipo)
plt.plot(x, f(x), 'k', label='f(x)')
plt.plot(x, iy, 'y--', label='interpolation')
plt.legend(... |
rows=int(input("Enter rows : "))
cols=int(input("Enter cols : "))
#Rectangle
for i in range(rows):
for j in range(cols):
print("* ",end="")
print()
#Hollow Rectangle
print("-------------------------------")
for i in range(1,rows+1):
for j in range(1,cols+1):
if(i==1 or i==rows or j=... |
# 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: TreeNode, q: TreeNode) -> bool:
def dfs(left, right):
if not left and not right:
... |
def bubble_sort(A):
'BUBBLE-SORT(A)'
for i in range(len(A)):
for j in range(len(A) - 1, i, -1):
print(j)
if A[j] < A[j - 1]:
A[j], A[j - 1] = A[j - 1], A[j]
if __name__ == '__main__':
A = [1, 4, 7, 2, 5, 3, 8, 6, 0, 9]
bubble_sort(A)
print(... |
import pyshorteners
url = input("Please Enter your URL : ")
shortener = pyshorteners.Shortener()
a = shortener.tinyurl.short(url)
print(f'The Short URL is : {a}')
|
import unittest
from mars_rover import Rover, Direction, Move, Turn
class Mars(unittest.TestCase):
"""
Seems to not be able to use a BeforeAll to initiate the Kata
"""
# This is the landscape, being 0,0 the top left position, and being 0 a place without obstacles. Both are 0 based
landscape = ((... |
import unittest
import reverse_words
class ReverseWord(unittest.TestCase):
def test_one_word_equals(self):
self.assertEqual(reverse_words.reverse("hi"), "hi")
def test_one_word_trailing_deleted(self):
self.assertEqual(reverse_words.reverse("hi "), "hi")
def test_two_words(self):
... |
import unittest
import sum_of_numbers
class GetSum(unittest.TestCase):
"""
Seems to not be able to use a BeforeAll to initiate the Kata
"""
def test_sum_two(self):
self.assertEqual(sum_of_numbers.get_sum(1, 2), 3)
def test_sum_two_negative(self):
self.assertEqual(sum_of_numbers.... |
import matplotlib.pyplot as plt
total=int(input("Enter : "))
avg = 0
def fact_1(set_a):
xy = set_a-1
x = set_a-1
y = 1 arr = []
while(x>=y):
val = xy% set_a
#print(val)
if val not in arr:
arr.append(val)
xy = xy + x -y -1
x= x-1
y = y+1
return (set_a/2)/len(arr)
#print("CHECK")
#c = 1
#d = 3
... |
##
def fibonacci():
a = 0
b = 1
while True:
yield a
a, b = b, a + b
count = 1
for f in fibonacci():
print("--->" + str(f) + '\n')
count= count + 1
if count >=100:
break
|
#
# Copyright (C) 2010-2013 Vinay Sajip. See LICENSE.txt for details.
#
import logging
import logutils
class LoggerAdapter(object):
"""
An adapter for loggers which makes it easier to specify contextual
information in logging output.
"""
def __init__(self, logger, extra):
"""
Initi... |
def get_parents(family_tree, child_node):
parents = [node[0] for node in family_tree if node[1] == child_node]
return parents
def earliest_ancestor(ancestors, starting_node, path = [], visited = set()):
# ancestors = array of tuples where tuple[0] is the parent and tuple[1] is the child it's connected to... |
# By Aakash Rohila
game_input =['Null', ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' ]
# Board of my Game
def game_board(game_input):
print("_"+ game_input[7]+ "_" + "|" + "_"+ game_input[8]+"_" + "|" + "_" + game_input[9] + "_" )
print("_"+ game_input[4]+ "_" + "|" + "_"+ game_input[5]+"_" + "|" + ... |
entered_string = input('Enter a paragraph\n')
lower_entered_string = entered_string.lower()
vowel_count = 0
for ch in lower_entered_string:
# if ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u':
if ch in 'aeiou':
vowel_count += 1
print('Vowel count is', vowel_count)
print('length of st... |
# n = int(input('Table for?\n'))
#
# for i in range(1, 11):
# print('%d X %d = %d' % (n, i, n * i))
letter = '''
Dear %s,
I am fine and hope you are also fine ......
..................
.........................
............... see you soon on vacation.
... |
sample_list = [13, 15, 17, 90, 100, 97, 92, 1, 50]
highest = 0
for mark in sample_list:
if mark > highest:
highest = mark
print('Highest is', highest)
|
n = 1
for i in range(5):
print(n ** 2)
n = n * 10 + 1
for i in range(10, 0, -1):
print(2 ** i)
|
entered_value = input('Do you want buy it?')
if entered_value == 'y' or entered_value == 'yes':
print('Its price is $420.')
else:
next_input = input('Do you want another product?')
if next_input == 'y' or next_input == 'yes':
print('1) Iphone X ($1000)\n'
'2) Samsung S9 ($900)')
e... |
"""Position-Wide Feed-Forward layer.
"""
import torch.nn as nn
import torch.nn.functional as F
class PositionWideForward(nn.Module):
"""A PositionWideForward class is used to provide a position-wise feed forward layer for a neural network.
References:
A. Vaswani, et al. Attention is all you need. Ad... |
"""Multi-Head Attention layer.
"""
import math
import torch
import torch.nn as nn
import textformer.utils.constants as c
class MultiHeadAttention(nn.Module):
"""A MultiHeadAttention class is used to provide multi-head attention-based mechanisms in a neural network layer.
References:
A. Vaswani, et... |
class Stack(object):
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
length = len(self.items)
return self.items[len... |
# coding: utf-8
# In[ ]:
#1. Load the python libraries - Done (Data pulled is only for top 200 for 2012)
#2. Create dummy variables and account for missing data - created a dummy variable and appended to my dataframe. Also
#3. Describe your data - Done
#4. Which of our variables are potentially collinear? - After ... |
t=(1,2,3,4,5,6)
print (max(t)) #max element
print (min(t)) #min element
print (t*2) #multiply the elements of tuple
print (2 in t) #if that element is present in the tuple
print (8 in t)
print (t[-5]) #backward indexing
print (t[3]) #forward indexing
print (t[2:4]) #slicing
|
def isPalindrome(string):
if len(string)<=1:
return True
else:
return string[0]==string[-1] and isPalindrome(string[1:-1])
while True:
print("\nPress 9 to quit.\n")
s = input("Enter a string to check if it's Palindrome or not\n");
s = s.lower();
if s=="9":
break
elif(isPalindrome(s) == True):
... |
a = []
c = []
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
c.append(b)
s = a+c
n = len(s)
for i in range(n):
for j in range(0, n-i-1):
if ... |
class OxfordDictionary(object):
oxfordDict = {'Nishita': 'a human being','marathon': 'a running race that is about 4 miles','resist': 'to remain strong against the force','run': 'to move with haste; act quickly'}
def __init__(self):
print(self.oxfordDict)
def random(self):
self.oxfordDict['shoe'] = 'a... |
n = int(input("Enter any number to check if it is palindrome or not :-\n"))
rev = 0
temp = n
while(temp>0):
rev = rev * 10
rev = rev + (temp % 10)
temp = temp // 10
print("Reverse of given input is : - ",rev)
if(rev == n):
print("Number is palindrome")
else:
print("Number is not palindrome")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.