text stringlengths 37 1.41M |
|---|
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
... |
class Solution:
def fib(self, N: int) -> int:
memo = {0: 0, 1: 1}
return self.fib_helper(N, memo)
def fib_helper(self, N, memo):
if N in memo:
return memo[N]
else:
memo[N] = self.fib_helper(N - 1, memo) + \
self.fib_helper(N - 2, memo)
... |
# run with python3 turtle_draw.py
from turtle import *
import math
# describe the arm and its joints
inner_radius = 180 # the blue (inner) arm
outer_radius = 160 # the red (outer) arm
extent = 160 # the arc covered by each of the two joints
joint_angle = 90 # the centre of the outer arm relative... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import date
from random import randint
class Intervalo:
def __init__(self):
self.t_i = ""
self.t_f = ""
self.listaDePontosTemporaisAleatorios = []
self.listaDePontosTemporais = []
self.listaDeIntervalos = []
... |
"""
We'll start with this tree::
4
2 7
1 3 5 8
like this::
>>> t = Node(4,
... Node(2, Node(1), Node(3)),
... Node(7, Node(5), Node(8))
... )
>>> t.sum_dfs()
30
>>> t.sum_bfs()
30
"""
class Node(object):
"""Bina... |
import random
def compare():
list1 = list([random.randint(0, 50) for i in range(1, 10)])
print(list1)
list2 = list([random.randint(0, 50) for j in range(1, 15)])
print(list2)
list3 = list()
for i in list1:
for j in list2:
if i == j:
list3.append(i)
print(... |
# Leitura dos Arquivos
fileReadState = open('entrada.txt.txt' , 'r')
fileReadAlphabet = open('automato.txt.txt', 'r')
#Cria arquivo para escrita
fileWrite = open('saida.txt.txt' , 'w')
# Leitura das linhas dos arquivos
ReadState = fileReadState.read()
ReadAlphabet = fileReadAlphabet.read(... |
diasv=int(input("Insira quantos dias de vida você tem: "))
anos=diasv/365
mes=(diasv%365)/30
dias=((diasv%365)%30)
print("Você tem %1.f anos %1.f meses e %1.f dias de vida."%(anos,mes,dias))
|
base=int(input("Insira a base: "))
altura=int(input("Insira a altura: "))
area=base*altura
if base!=altura:
print("A area do retangulo é: ",area)
else:
print("A area do quadrado é: ",area) |
def soma(n1,n2,n3):
s=n1+n2+n3
print("O resultado da soma dos números anteriormente é : ",a)
def maior(n1,n2,n3):
if n1>n2 and n1>n3:
print("O maior número é o: ",a)
elif n2>n1 and n2>n3:
print("O maior número é o: ",b)
else:
print("O maior número é o: ",c)
def me... |
ano=int(input("Insira ano: "))
if ano%4==0 and ano%100!=0 or ano%400==0:
print("É bissexto") |
import csv
inputfile = '\\Users\\guila\\PycharmProjects\\python_poll\\election_data.csv'
outputfile = '\\Users\\guila\\PycharmProjects\\python_poll\\election_output.txt'
# Create empty list for csv file
polls = []
# Create empty dictionary to record only candidate names
dict_polls = {}
# Create empty dictionaty to sum... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 2 22:03:48 2021
@author: ThinkPad
"""
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
solutions = list()
queens = [-1]*n #初始化皇后的位置
col = set()
diag1 = set()
diag2 = set()
def backtrack(... |
# -*- coding: utf-8 -*-
"""
实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,x^n)。
"""
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1
if n == 1:
return x
if n < 0:
x = 1/x
n = -n
temp = self.myPow(x, n//2... |
# -*- coding: utf-8 -*-
'''
Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
'''
class Solution: # Normal method
def addTwoNumbers(self, l1, l2):
result = ListNode(0)
re = result
carry = ... |
'''
Created on Feb 8, 2016
@author: Carles Poles-Mielgo
UCI - Introduction to Python
Week 3 Assignment
NOTE: My compiler is Python 3.5.0 |Anaconda 2.4.0.
'''
# Question 1.
for x in range(10):
print(x)
# Question 2.
for x in range(10):
if x == 0:
print('zero')
elif (x % 2) == ... |
from numpy import *
import math
import funciones
import gauss
import os
os.system("clear")
print("=======================================================================")
print("========================== Metodo de Newton ===========================")
print("================== Sistema de Ecuaniones no Lineales =======... |
def selection_sort(arr):
for i in range(len(arr)):
minimum = i
for j in range(i+1,len(arr)):
if arr[j] < arr[minimum]:
minimum = j
arr[i],arr[minimum] =arr[minimum],arr[i]
return arr
a= [3,1,5,2,6,4,9,8,7]
b= [5,6,9,8,7,2,4,3,1]
c= [9,7,8,4,6,1,3,2,5]
print(selection_sort(a))
print(selection_sort(... |
# Selection Sort
# Complexity of Selection Sort - O(n2)
# Number of Swaps - O(n)
# It is not a stable sort
def selection(iteration_list):
length = len(iteration_list)
for i in range(length - 1):
min_position = i
for j in range(i, length):
if iteration_list[j] < iteration_list[min_p... |
# Bubble Sort
# Complexity of Bubble Sort - O(n2)
# It is a stable sort
# Number of Swaps - O(n)
def bubble(iterate_list):
for i in range(len(iterate_list) - 1, 0, -1):
for j in range(i):
if iterate_list[j] > iterate_list[j+1]:
iterate_list[j], iterate_list[j+1] = iterate_list[... |
"""Eular Problem 6 - Sum square difference:
Find the difference between the sum of the squares of the first one
hundred natural numbers and the square of the sum.
"""
import timer
DESC = 'Sum square difference'
SOLUTION = 25164150
def sum_of_squares(limit):
""" Returns the sum of all squares in the range... |
"""Eular Problem 8 -
What is the 10001st prime number?
"""
import primes
import timer
DESC = '10001st prime:'
SOLUTION = 104743
@timer.timeit
def solve():
targetprime = 10001
result = 0
for i, result in enumerate(primes.primes()):
if i == targetprime - 1:
break
return result
|
################################
# Title -- The Old Mansion
# Author -- Austin Rosenbaum
# Started -- July 5, 2018
# Modified -- July 29, 2019
# Finished -- ??/??/????
################################
# Imports
# pygame?
import time, random
# Custom imports
from entity.player import Player
from map.spot import ... |
print 'hello nancy'
a = 1;
b = 3;
if a<b:
print a
else:
print b
count = 0
while (count < 9):
print "this count is:", count
count= count+1
print "this is the end"
a="I am the start"
b="I am the end"
print a,b
|
def merge(left_list, right_list):
sorted_list = []
left_list_index = right_list_index = 0
left_length, right_length = len(left_list), len(right_list)
for _ in range(left_length + right_length):
if left_list_index < left_length and right_list_index < right_length:
if left_list[left_l... |
def singleton(class_):
"""Singleton decorator function
Arguments:
class_: singleton class
"""
instance = {}
def get_instance(*args, **kwargs):
if class_ not in instance:
instance[class_] = class_(*args, **kwargs)
return instance[class_]
return get_instanc... |
class VectorError(Exception):
def __init__(self, message):
self.message = message
class Vector:
def __init__(self, *components):
for arg in components:
if not isinstance(arg, int) and not isinstance(arg, float):
raise TypeError
self.components = comp... |
import re
import argparse
def generator(range, first = 0, second = 1):
while second < range:
temp = second
second += first
first = temp
yield first
def fibonacci(range):
f = generator(range)
for num in f:
print(num)
def merge(left, right):
resul... |
# -*- coding: utf-8 -*-
def main():
ipt = input().split(' ')
N, M = tuple(map(lambda x: int(x), ipt))
route_dict = {}
if M != 0:
for _ in range(M):
ipt = input().split(' ')
a, b = tuple(map(lambda x: int(x), ipt))
if not a in route_dict:
route... |
for _ in range(input()):
a = raw_input()
b = raw_input()
l = len(a)
answer = ""
for i in range(l):
if a[i] == b[i]:
if a[i] == 'B':
answer += 'W'
else:
answer += 'B'
else:
answer += 'B'
print answer
|
for _ in range(input()):
s = raw_input()
l = len(s)
for i in range(l):
if s[i] == "s" and i > 0 and s[i-1] == "m":
s = s[:i-1] + "#." + s[i+1:]
elif s[i] == "s" and i < l-1 and s[i+1] == "m":
s = s[:i] + ".#" + s[i+2:]
answer = 0
for c in s:
if c == "... |
for _ in range(input()):
n = input()
a = []
if n%2 == 1:
for i in range(1,n-3,2):
a.append(i+1)
a.append(i)
a.append(n-1)
a.append(n)
a.append(n-2)
else:
for i in range(1,n,2):
a.append(i+1)
a.append(i)
for i in ... |
allowed = ["CES", "CE", "CS", "ES", "C", "E", "S"]
for i in range(input()):
s = raw_input()
newS = ""
lastC = ""
for c in s:
if c != lastC:
newS += c
lastC = c
answer = "no"
for correct in allowed:
if newS == correct:
answer = "yes"
... |
for _ in range(input()):
a = raw_input().split()
answer = ""
for i in range(len(a)-1):
answer += a[i][0].upper() + ". "
answer += a[-1][0].upper() + a[-1][1:].lower()
print answer
|
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 28 17:39:36 2019
@author: 33762
"""
import blocageTour as bT
import blocageFou as bF
def place_dispo(pos,echiquier,couleur):
"""
place_dispo(List[int,int],List[List[String]],String)
-> return String
Returns if the box whose position i... |
class Foo:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
print('call __init__ with args({}, {}, {})'.format(
self.a, self.b, self.c))
def __call__(self, a, b):
self.a = a
self.b = b
print('call __call__ with args({}, {})'.forma... |
# Create of Master User and save Passwords. After Creation of Master User, you
# add your username and passwords along with websites on which you have made
# your account and want to store the data.
import sqlite3
import string
import secrets
database = sqlite3.connect('master_database.db')
cur = database.curs... |
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
from typing import List
from find_optimal import find_optimal
from find_approx import find_approx
from our_cost import our_cost
def compare_graph(graph_type: str, num_nodes: int, **kwargs):
G = get_graph_by_type(graph_type=graph_type, num_... |
#1. Create a greeting for your program.
#2. Ask the user for the city that they grew up in.
#3. Ask the user for the name of a pet.
#4. Combine the name of their city and pet and show them their band name.
#5. Make sure the input cursor shows on a new line, see the example at:
# https://band-name-generator-end.ap... |
"""
Created on Sun Oct 21 17:04:27 2018
@author: Wuethrich Pierre
This is some example code of image classification using a simple CNN,
using the MNIST data (hand-written digits)
"""
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.exa... |
def longest_subsequence(arr):
n = len(arr)
lista_crescatoare = [1]*n
for i in range (1 , n):
for j in range(0 , i):
if arr[i] > arr[j] and lista_crescatoare[i]< lista_crescatoare[j] + 1 :
lista_crescatoare[i] = lista_crescatoare[j]+1
maximum = 0
... |
# Strip() function is used to remove the white space from the string.
x = " hello world! "
# print
# print(x.lstrip())
# print(x.rstrip())
# print(x.strip())
#The split() method splits the string into substrings if it finds instances of the separator:
print(x.split( ))
print(x.split("world"))
print(x.split("e"))
|
# Quadratic equation: ax**2 + bx + c
# solution is: -b +- under root b square minus 4 ac upon 2a
import cmath
a = int(input("Enter no1:"))
b = int(input("Enter no2:"))
c = int(input("Enter no3:"))
# calculate discrimination
d = (b ** 2) - (4 * a * c)
# two solutions
solu1 = (-b + cmath.sqrt(d)) / (2 * a)
solu2 = (-b... |
num = int(input("Enter number:"))
sum = 0
if num < 0:
print("Enter positive number!")
else:
for i in range (1, num+1):
sum = sum + i
print("the sum of natural no.", num,":", sum)
|
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
x = tf.placeholder(tf.float32,[None,784])
w = tf.Variable(tf.zeros([784,10]), tf.float32)
b = tf.Variable(tf.zeros([10]), tf.float32)
y = tf.nn.softmax(tf.matmul(x, w)+ b)
y_ ... |
import random
import os
def get_random_digits():
correct_answer = []
while len(correct_answer) < 3:
digit = random.randint(0, 9)
if digit not in correct_answer:
correct_answer.append(digit)
return correct_answer
def get_user_input():
while True:
user_guess = input... |
imagenes=['im1','im2','im3']
dic={}
indice=0
for i in imagenes:
print("Ingrese la primer coordenada del elemento" " '",imagenes[indice],"'")
primer=int(input())
print("Ingrese la segunda coordenada del elemento" " '",imagenes[indice],"'")
segundo=int(input())
tupla=(primer, segundo)
... |
# -*- coding: utf-8 -*-
class Classifier:
""" This class is the abstract version of a classifier.
All classifiers in this project should inherit this class to offer a
uniform API.
"""
def __init__(self, name):
""" Constructor.
Arg:
name the name of the... |
name = "John Doe"
age = 47
occupation = "Spy"
print(f"{name}, aged {age} is a {occupation}")
number = 5
number= number + 20
print (f"The number is {number}.")
number_of_oranges = 3333
number_of_people = 4
print(int(number_of_oranges/number_of_people))
print(int(number_of_oranges%number_of_people))
sentence = "This ... |
# Collaborators (including web sites where you got help: (enter none if you didn't need help)
# none
print("Hello welcome to madlibs! You ready?")
input()
print("Great lets get started!")
adjective = input("type an adjective ")
nationality = input("type a nationality ")
person = input("type a person ")
noun = input ("... |
import copy
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def sortList(self, head):
if not head:
return None
val_list = []
while head:
val_list.append(head.val)
head = head.next
val_lis... |
"""
回溯模板
result = []
def backtrack(路径, 选择列表):
if 满足结束条件:
result.add(路径)
return
for 选择 in 选择列表:
做选择
backtrack(路径, 选择列表)
撤销选择
"""
# 全排列
list = [1, 2, 3]
ret = []
ret.extend(list)
def func(pp, ret):
if len(pp) == len(list):
print(pp)
for i, va in enumerate(... |
# 最常见的形式,采用左右闭区间(<=, +1 -1都于此有关)
def binarySearch(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (right+left)//2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
ret... |
def get_numbers_list(number_length, digit):
table = []
for i in range(0, 2**number_length):
if '{0:0{1}b}'.format(i, number_length)[digit] == '1':
table.append(i)
return table
def is_binary_one(i, table):
while True:
print "\n\nTable {0}: {1}".format(i, table)
answe... |
from collections import defaultdict
# Setting up Tuple of Tuples
classes = (
('V', 1),
('VI', 1),
('V', 2),
('VI', 2),
('VI', 3),
('VII', 1),
)
# Calling for a defaultdict list
rollno = defaultdict(list)
# For loop to append name with 'id' numbers
for name, id in classes:
rollno[name].ap... |
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import random
class Application(Frame):
def __init__(self, master):
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
#enter name label r... |
'''
Created on 20-Mar-2019
@author: sourav nandi
'''
def factors(n):
l=[]
for i in range(1,n+1):
if(n%i==0):
l.append(i)
return l
try:
n=input()
if(int(n)<=1000):
l=factors(int(n))
if(l==[1,int(n)]):
print("yes")
else:
print("... |
import random
def rand5():
return random.randint(1, 5)
def rand7():
# Implement rand7() using rand5()
while (True):
i = (rand5()-1)*5+rand5()
if i<=21:
return (i)%7+1
print ('Rolling 7-sided die...')
print (rand7()) |
import unittest
def find_rotation_point(lists):
n = len(lists)-1
l = 0
while n >= l:
y = int (l + (n - l)/2)
if lists[y-1] >= lists[n] and lists[y] <= lists[n]:
return y
elif lists[y] > lists[n]:
l = y+1
else:
n = y-1
... |
from abc import ABC, abstractmethod
class CaffeineBeverage(ABC):
def prepare_recipe(self):
self.boil_water()
self.brew()
self.pour_in_cup()
if self.customer_wants_condiments():
self.add_condiments()
def boil_water(self):
print('Boiling water')
def pour... |
from abc import abstractmethod
# According to ISP
# Many specific interfaces are better than one
# do it all interface.
class Printer:
@abstractmethod
def print(self, document):
pass
class Scanner:
@abstractmethod
def scan(self, document):
pass
# same for Fax, etc.
# Here defining ... |
import discord # api wrapper for the discord api
import os # to work with environment variables
import requests # make a http request to api
import json # to process data returned from api
import random # for bot to choose message randomly
from replit import db
from keep_alive import keep_alive # import the keep_a... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 8 06:25:58 2018
@author: habhavsar
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
q = queue.Queue()
q.put(1)
while not q.empty(... |
import sys
def output_func(arr, threshold, limit):
sum_val = 0
for i, element in enumerate(arr):
#Subtract the threshold
val = max(0, element - threshold)
#If we reached the limit, only print zeros
if (sum_val == limit):
print(0)
elif sum_val + val < limit... |
__author__ = 'Kalyan'
max_marks = 20
problem_notes = '''
Given a sequence [a1, ... ,an], the diff sequence is [|a1- a2|, |a2-a3|, .... |an -a1|] (loop around at the end).
(|x| denotes absolute value of x)
A sequence of 0s is called a null sequence.
If we apply the diff process repeatedly on a given sequence, it m... |
inputRow = int(input("Masukkan Angka : "))
for x in range(1, inputRow+1):
for y in range(1, x + 1):
print(x * y, end=" ")
print()
|
from datetime import datetime
import getpass
import locale
import module
statusMasuk = True
def formatRupiah(angka):
locale.setlocale(locale.LC_NUMERIC, 'IND')
rupiah = locale.format_string("%.*f", (0, angka), True)
return "Rp. " + rupiah
while statusMasuk:
print("\n1. Login")
print("2. Regist... |
jawab = 'y'
def operatorTambah(angka1,angka2):
return angka1+angka2
def operatorKurang(angka1,angka2):
return angka1 - angka2
def operatorBagi(angka1,angka2):
return angka1 / angka2
def operatorKali(angka1,angka2):
return angka1 * angka2
while jawab == 'y':
angkaPertama = int(input("Masukkan An... |
import time, math
# ------------------------------------------------------------------------------------------
# FUNCTIONS
# ------------------------------------------------------------------------------------------
def create_sequences(parent_tree_position, parent_value, parent_bit_list):
''' Generates Collatz pref... |
import math
import time
# ------------------------------------------------------------------------------------------
# FUNCTIONS
# ------------------------------------------------------------------------------------------
global_bit_list = []
def powers_of_two(n):
""" Creates and returns a list of powers of two fro... |
import time
start_time = time.time()
sum_of_fifths = []
for number in range(2, ((9**5)*6)+1):
sum_of_digits = 0
for i in range(len(str(number))):
sum_of_digits += int(str(number)[i])**5
if sum_of_digits == number:
sum_of_fifths.append(number)
print()
print('solution: '+ str(sum(sum_of_fifths)))
print('runtime:... |
import time
start_time = time.time()
a, b = 1, 1
hit = False
while hit is False:
b += 1
for delta_a in range(b-a):
if (((a+delta_a)**2 + b**2)**0.5) + (a+delta_a) + b == 1000:
hit = True
a += delta_a
print()
print('a,b,c = '+str(a)+','+str(b)+','+str(int((a**2 + b**2)**0.5)))
print('product of side lengths:... |
import time, matplotlib.pyplot as plt
print()
threshold = int(input('how many powers of 2 do you want to print? '))
start_time = time.time()
sum_of_digits = [0] * (threshold+1)
number_of_digits = [0] * (threshold+1)
for number in range(threshold+1):
power = 2 ** number
sum_of_digits[number] = sum([int(digit) for di... |
import re
from typing import Tuple
import pandas as pd
__all__ = ['sanitize_string', 'sanitize_string_column', 'extract_names']
__ALPHANUMERIC_REGEX = re.compile(r'[^0-9A-Za-z\s]')
__SPACING_REGEX = re.compile(r'\s+')
def sanitize_string(text: str,
upper: bool = False,
alpha... |
import numpy as np
import scipy.special as sp
"""
The focus of the test is the proportion of zeroes and ones for the entire sequence. The purpose of this test
is to determine whether the number of ones and zeros in a sequence are approximately the same as would
be expected for a truly random sequence. The test asses... |
import re
from app import lista
class instrumento():
def __init__(self, tipo):
self.tipo = tipo
def tipoInstrumento(self):
if self.tipo == "viento":
return 1
elif self.tipo=="cuerda":
return 2
else:
return 3
... |
#declaracion de variables
cadena = r"hola \n f" #raw sirve para expresiones regulares
cadenaTripleComilla= """hola sirvo para hacer
saltos de linea"""
lista= [33,"roberto", "cachanosky", 3.12] #declaro list 1
print(lista[0:3]) #imprimo lista1
lista2= lista[0:2] #decl... |
class phalangeList:
phalangelist = []
def refill(self,plist):
templist = []
appflag = 1
for i in range(len(plist)):
for j in range(len(self.phalangelist)):
if plist[i] == self.phalangelist[j].fileID:
templist.appen... |
import csv
import os
#
# stock_pick.py
# DD 1318 @ KTH
# For P-assignment 2020
#
# The program needs two folders in the same file as where the program exists.
# One folder named data_files_in and one work_data_files.
# - In data_files_in you save csv files from nasdaq just as they are.
# - In the... |
n = int(input('Digite um número inteiro: '))
r = n % 2
if (r == 0):
print('O número digitado foi {}, ele é PAR'.format(n))
else:
print('O número digitado foi {}, ele é IMPAR'.format(n))
|
'''
Leia 3 valores de ponto flutuante A, B e C e ordene-os em ordem decrescente, de modo que o lado A representa o maior dos 3 lados. A seguir, determine o tipo de triângulo que estes três lados formam, com base nos seguintes casos, sempre escrevendo uma mensagem adequada:
se A ≥ B+C, apresente a mensagem: NAO FORMA T... |
#from math import sqrt, exp, tan, pi, log, sin, e
import string
import random
from random import randint
###
# Enter file names here
read_file = raw_input("Enter the file name to read from: ")
write_file = raw_input("Enter the file name to write to: ")
###
numberOfRotors = 40
chars = string.printabl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Funkce pro generovani site bodu ve 2D prostoru"""
import matplotlib.pyplot as plt
import numbers
def frange(start, stop, step):
i = start
while i < stop:
yield i
i += step
def generate_points(start, end, step):
if isinstance(step, numbers... |
'''
Bunny Prisoner Locating
=======================
Keeping track of Commander Lambda's many bunny prisoners is starting to get tricky. You've been tasked with writing a program to match bunny prisoner IDs to cell locations.
The LAMBCHOP doomsday device takes up much of the interior of Commander Lambda's space statio... |
There is a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus.
The player can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus '1' or '2'.
The player must avoid the thunderheads. Determine the minimu... |
def iq_test(numbers):
numbers = numbers.split(" ")
ctr_even = 0
ctr_odd = 0
ans = 0
for i in range (len(numbers)):
numbers[i] = int(numbers[i])
if numbers[i] % 2 != 0:
ctr_odd +=1
else:
ctr_even +=1
for j in range (len(numbers)): ... |
# def stringreverse(request):
# a = ""
# # for i in request[-1:-len(request)-1:-1]:
# for i in request[::-1]:
# a = a + i
# print(a)
# request = input("enter the string")
# stringreverse(request)
# from random import randint
# for i in range(5):
# print(random(5,1)) |
# a = [1, 2, 3, 4]
# print(sum(a))
def largest(a):
max = a[0]
for i in range(0, len(a)):
if a[i] > max:
max = a[i]
print(max)
a = [3,55,6,1,2]
res = largest(a)
# print(res)
from collections import Counter
l1 = [1, 2, 3, 4, 5]
l2 = [4, 5, 6, 7, 7, 8, 9]
print(Counter(l1),Counter(l2)) |
a,b=[],[]
for i in range(-4, 5):
if i >= 0:
a.append(i)
else:
b.append(i)
print(a,b)
|
def bubble(a):
try:
for i in range(0, len(a)-1):
if a[i] > a[i+1]:
temp = a[i]
a[i], a[i+1] = a[i+1], temp
for i in range(len(a)):
print(a[i], end=' ')
except Exception as e:
print(e)
a = [10, 3, 1, 5, 2, 8, 0, 7]
bubble(a)
|
class Employee:
bonus = 2
emp_count = 10
cname = 'google'
def __init__(self,name,pay):
self.name = name
self.pay = pay
self.mail = name+'@'+self.cname+'.com'
def display(self):
return f'employee name is {self.name} and salary is {self.pay} and mail-id is {self.mail}'... |
'''
******************************************************************************
code name:- genetic algorithm to evaluate a function
function :- x/(1+x**2)
******************************************************************************
'''
from random import random, randint,sample
import math
def calc... |
import requests
import datetime
class PyCanliiBase(object):
"""
The base object in the pycanlii library. All objects in the library inherit from it.
"""
def __init__(self, apikey, language):
self._key = apikey
self._lang = language
def _request(self, url, authenticated, *url_varia... |
class SudokuSolver(object):
""" SudokuSolver class. This class requires a list representation
of a sudoku, and will then try to solve it.
Usage:
Instantiate an object from the class and pass a start_board.
Then you can use the exposed methods.
Exposed methods:
... |
##Ashley Speigle
##Lab04: Simulation Part 2
import random
patients = ["Bob", "Herbert", "Joe", "Suzy", "Bertha", "Alice", "Don", "Billy", "Andrew",
"George","Fred", "Cain", "Adam", "Eve", "Peter", "Noel", "Ashley", "Linda",
"Richard", "Brandon"]
class patient:
def __init__(self,na... |
# Written by Aaron Barge
# Copyright 2019
import math
class Coord(object):
def __init__(self):
return
class Cartesian(Coord):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "(x = " + str(self.x) + ", y = " + str(self.y) + ")"
def __eq__(self, p2):
self_new = sel... |
def main():
weeks = [39.86, 33.11, 30.45, 36.39, 33.10, 0, 7.94, 36.49, 37.59, 27.36, 32.54, 25.83, 31.14, 26.34, 25.86, 28.21, 26.08, 27.65, 27.08, 8.00, 10.26, 18.46, 17.87, 25.73, 26.37, 9.30, 37.94, 22.71, 0, 33.56, 28.47, 29.19, 13.36, 22.35, 22.07, 21.90, 21.17, 22.83, 29.66, 21.53, 21.37, 21.89, 22.34, 24.16, ... |
#!/usr/bin/env python
# coding: utf-8
# In[14]:
class Human: #single person details class
name = "manoj"
age = 25 #attributes
gender = "male"
def Run(self): #function
print("manoj is running.....")
object = Human() #object
p... |
text = "This is a new text now\n"
filename = "foo.txt"
# apart from reading a file you can also
# store data in it. This can be done by
# adding a parameter in the open() function.
# a : append -> will append at the end
# w : write -> will overwrite (clears the file)
# r : read
# no parameter : automatically read
# ... |
# coding=utf-8
# Task 1
# create a string, which is a welcome message, with a placeholder for the name
# enter the name and print it.
# reminder:
# you can add placeholders and fill in variables like this:
# greeting = "hello"
# name = "my name"
# print(f"Greeting: {greeting}, Name: {name}")
name = "Alfred"
print(f"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.