text stringlengths 37 1.41M |
|---|
dict = {"name" : "Anubhav",
"same" : "smart",
"game" : "Enjoy"
}
inp = input("Enter The name : ")
print("Mean : ",dict[inp]) |
#n = 0
#while n <= 15:
# print('O valor de n é: {0}'.format(n))
# n += 1
x = []
for i in range(0,16):
x += [i]
print(x)
if x(int) % 2 == 0:
print(x,'é par')
else:
print(x, 'é impar') |
def prog3(a):
Counters = 0
for i in range(1, a+1):
if (a % i) == 0:
Counters += 1
if Counters == 2:
a = True
else:
a = False
return a
|
import math
def equation2D(a, b, c):
delta = (b**2) - (4*a*c)
if delta > 0:
m = math.sqrt(delta)
x1 = (-b-m)/(2*a)
x2 = (-b+m)/(2*a)
print("This equation has two answers:" + str(x1) + "and" + str(x2))
elif delta < 0:
print("This equation has no answer!")
else:
x = (-b)/(2*a)
print("This equation has o... |
#Erick Mikoshi - Algorithms Project 1
#Implemented algorithm to measure the validity of butterfly data
#Declaring and initializing variables
user_input = raw_input('What file do you want to use?')
raw_G = [ ]
G = [ ]
colors = [ ]
related = [ ]
raw_list = [ ]
seen = [ ]
count = 0
final = 0
f = open(user_input, 'r')
#R... |
fizzbuzz = 0
count = True
while fizzbuzz <= 100:
if fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0:
print "Fizz Buzz"
fizzbuzz += 1
elif fizzbuzz % 3 == 0:
print "Fizz"
fizzbuzz += 1
elif fizzbuzz % 5 == 0:
print "Buzz"
fizzbuzz += 1
else:
print fizzbuzz
fizzbuzz += 1
|
lado = input('Digite o valor correspondente ao lado de um quadrado: ')
ladoInt = int(lado)
perimetro = ladoInt * 4
area = ladoInt * ladoInt
print('perímetro:', perimetro, '- área:', area) |
pocketmoney=int(input("enter the pocketmoney"))
if(pocketmoney>500):
print("i am a rich kid")
elif(pocketmoney>100):
print("i am a middle class kid")
else:
print("i am good") |
# Import packages necessary
import sumy, wikipedia, pyttsx3
from sumy.parsers.plaintext import PlaintextParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.lex_rank import LexRankSummarizer
converter = pyttsx3.init()
converter.setProperty('rate', 160)
converter.setProperty('volume', .09)
de... |
import numpy as np
class Dense:
""" Fully connected layer """
def __init__(self, n_input_units, n_hidden_units, learning_rate = 1e-3):
"""Creates and initializes weights / biases of layer
Parameters
----------
n_input_units : int
Number of in... |
# -*- coding: utf-8 -*-
import unittest
from calc import calculate, ERROR_MESSAGE
class CalculatorTestCase(unittest.TestCase):
def test_fractions_add(self):
r = calculate("3.04+-4.04")
self.assertEqual(r, '-1.00')
def test_fractions_sub(self):
r = calculate("3.04--4.06")
self.assertEqual(r, '7.10')
... |
#import rependencies
# library for pulling out data from html and xml
from bs4 import BeautifulSoup
# HTTP library that deals with requests in python
# pull, push, authenticate
import requests
# for regular expression operations
import re
# intrinsic opertations in python such as
# addition, comparision, >, < opera... |
"""
Given an infinite supply of ‘n’ coin denominations and a total money amount,
we are asked to find the minimum number of coins needed to make up that amount.
"""
import sys
def minCoin(coins, total):
def dp(total):
if total == 0:
return 0
else:
temp = sys.maxsize
... |
"""
Problem Statement
Given a string, find the minimum number of characters that we can remove to make it a palindrome.
Example 1:
"abdbca"
Input: "abdbca"
Output: 1
Explanation: By removing "c", we get a palindrome "abdba".
if st[i] == st[j]:
return min (dp(i+1,j-1),1+dp(i,j-1),1+dp(i+1,j))
else:
return min (... |
import numpy as np
class ActivationFunction:
@staticmethod
def forward(Z):
return Z
@staticmethod
def backward(dA, old_value):
return 1, old_value
class Sigmoid(ActivationFunction):
@staticmethod
def forward(Z):
"""
Sigmoid activation function
:para... |
# import tkinter
'''LABELKA'''
# window = tkinter.Tk()
# window.title("Pierwsze okno")
# window.geometry("400x400+200+200")
# myLabel = tkinter.Label(window, text="Jakis napis", fg="red", bg="pink", width=50, font=("Arial", 20), anchor="s")
# myLabel.pack()
# myLabel.place(relx=0, rely=0.45)
# window.mainloop()
'''PR... |
def generate_list_of_numbers():
return range(1, 100)
def num_to_fizz_string(number):
if number % 3 == 0 and number % 5 == 0:
return 'FizzBuzz'
if number % 3 == 0:
return 'Fizz'
if number % 5 == 0:
return 'Buzz'
return str(number)
def run_fizzbuzz():
numbers = genera... |
#CTI-110
#M2HW2-Tip Tax Total
#Jalessa Hawkins
#September 9, 2017
#Get the total food cost
foodcost= float(input('Enter food cost: '))
#Calculate sales tax
salesTax= foodcost * 0.07
print('The amount of sales tax due is $', format(salesTax, ',.2f'))
#Calcu... |
from abc import abstractmethod
import numpy as np
import math
class Gradiente():
def __init__(self,arr_dz,arr_dw,db):
self.arr_dz = arr_dz
self.arr_dw = arr_dw
self.db = db
def __str__(self):
return "dz: "+str(self.arr_dz)+" db: "+str(self.db)+" arr_dw: "+str(self.arr_dw)
### F... |
#!/usr/bin/env python
''' Program will simulate transactions between random agents.
Assumptions:
N agents exchange money in pairs
All agents start with same amount of money m0 > 0
at given timestep, random agents exchange random (uniform) amount of money '''
''' Changelog:
V1.1 Added num_experiments to run multiple ... |
#dict
print(dict())
x=dict()
print(type(x))
pol_ang = {
#klucz : wartość
"klucz": "wartość",
"wartość": "value",
"pies": "dog"
}
print(pol_ang)
print(pol_ang["pies"])
if "dog" in pol_ang:
print(pol_ang["dog"])
print(pol_ang.get("dog"))
print(pol_ang.get("dog", "Brak takiego hasła"))
print(pol_ang.g... |
s="Hello!"
print(s[0:5]) #od indeksu 0 do 4 wlacznie
print(s[-3]) #3-eci znak od konca
s = "Ruda tańczy jak szalona"
arr = s.split(" ")
print(arr)
print(arr[0])
print(s[0:16:2]) #z indeksu od 0 do 16 ale co drugi znak
print(s[::3]) #caly string co 3-ci znak
#reverse w Pythonie
print(s[::-1])
print("zajecia dzis sie... |
"""
write a program that takes an array A and an index i into A, and rearranges the elements such that all elements
less than A[i](the pivot) appear first, followed by elements equal to the pivot, followed by elements greater
than the pivot.
"""
"""
Complexities:
Time: O(N)
Space: O(1)
"""
def sort_aroun... |
"""
Traverse a binary tree in level-order fashion
"""
class Node:
def __init__(self, data=None, left=None, right=None):
self.val = data
self.left = left
self.right = right
def level_order_traversal(root):
"""
1 Visit the root
2 While traversing level l, keep all the... |
""""
test if a binary tree satisfies the BST property
Complexities:
Time:
Space:
"""
class Node:
def __init__(self, data=None, left=None, right=None):
self.val = data
self.left = left
self.right = right
def if_bst(tree):
def are_keys_in_range(tree, low, high):
if no... |
"""
Given an array nums of non-negative integers, return an array consisting of all the even elements of nums,
followed by all the odd elements of nums.
You may return any answer array that satisfies this condition.
Complexities:
Time: O(N)
Space: O(1)
"""
def sort_by_parity(input_array):
j = len(inp... |
"""
Trevor Murphy
Project1, CS 250
February 2, 2015
FILE: main.py
Contains the main function that opens a text file,
builds a wordlist, prints the max and min frequency
of words to output, then saves each word with
its corresponding frequency to two text files.
Result1 contains normal order, result2 contains
alphabetic... |
import random
import time
import statistics
class Count:
"""
Classe para armazenar as iterações do algoritmo, as paredes do labirinto
e o custo da função de otimização (f(n)) de cada posição
"""
def __init__(self, contar, posicoes_proibidas, custo_posicao, distancia_real):
self.contar = 0... |
def get_type(sentence):
'''
Функция определяет тип предлоожения.
'''
last_char = sentence[-1]
if last_char == '?':
sentence_type = 'question'
elif last_char == '!':
sentence_type = 'exclamation'
else:
sentence_type = 'normal'
result = ('Sentence is {}'.format(sent... |
# Ex3, study-drill
# Find something you need to calculate and write a new .py file that does it
# 2018-08-17
# How many vacation days do I have left?
print("vacation days left:", 17)
# How much is this in hours?
print("hours vacation left:", 17 * 8) # 136 hours
# How many days are left in 2018?
print("days left in... |
# Edvin Kääpa, Sergei Smirnov sptvr19
#1
x = 1000
while True:
print(x)
x +=3
if x == 1018:
break
#2
x = 1
while True:
print(x)
x +=2
if x == 113:
break
#3
x = 90
while True:
print(x)
x -=5
if x == -5:
break
#4
x =... |
L=[]
for i in range(3):
L.append(input())
if L.count("RED")>L.count("BLUE"):
print("RED")
else:
print("BLUE")
|
dct={}
dct["A"]=int(input())
dct["B"]=int(input())
dct["C"]=int(input())
dct=sorted(dct.items(), key=lambda x:x[1])
for i in range(3):
print(dct.pop()[0])
|
class UNOSim:
""" Class doc """
def __init__ (self,N):
""" Class initialiser """
self.player_N = N-1
self.prev_card = ""
self.magnifi = 0
self.rev = False
self.players = [ 0 for x in range(N)]
self.turn = -1
def drop(self,card):
... |
#!/usr/bin/python3
A=input()
B=input()
if (len(A)>=2 and A[0]=="0") or (len(B)>=2 and B[0]=="0"):
print("NG")
exit()
try:
A=int(A)
B=int(B)
except ValueError:
print("NG")
exit()
if not(0<=A<=12345) or not(0<=B<=12345):
print("NG")
exit()
print("OK")
|
#!/usr/bin/python3
N=int(input())
for i in range(N,0,-1):
for j in range(i):
print(N,end="")
print() |
# This is a piece of code
print('Hello World')
a=8
b=7
c=a+b
# There was an error while printing c
print('the sum of the 2 nummbers is:'+str(c))
|
"""
Tejveer Singh
CS 100 2015F Section 009
HW 09 Cartoon Names
"""
#HW 1
def nameDictionary(lst):
x = lst.split(",")
nameD = {}
for i in range(len(x)):
if x[i] not in nameD and i %2 == 1:
nameD(x[i]) += [x[i +1]]
return(nameD)
namelist = ['Belcher, Bob', 'Simpson, Homer', 'Fry, Ph... |
#!/usr/local/bin/python
# Each new term in the Fibonacci sequence is generated by adding the previous two terms.
# By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not exceed
# four million, find the su... |
import threading
import time
import random
class LifoQueue:
def __init__(self):
self._list = []
self._lock = threading.Lock()
def put(self, item):
self._lock.acquire()
self._list.append(item)
self._lock.release()
def get(self):
self._lock.acquire()
... |
"""
Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge
is a pair of nodes), write a function to find the number of connected components in an undirected graph.
URL : https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/
"""
import sys
from queue import Queu... |
"""
There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first
take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible
for you to finish al... |
"""Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, ... |
'''
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
URL: https://leetcode.com/problems/linked-list-cycle-ii/
'''
# Definition for singly-linked list.
# class ListNode:
# de... |
"""
Write an efficient algorithm that searches for a value in an m x n matrix.
This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[
[1, 3, 5... |
"""
Implementation of k-nearest neighbours classifier
"""
import numpy as np
from scipy import stats
import utils
class KNN:
def __init__(self, k):
self.k = k
def fit(self, X, y):
self.X = X # just memorize the trianing data
self.y = y
def predict(self, Xtest):
X = self.... |
from challenge import solution, solutionArray
# Example tests, will be different for different input types
# FIXME Tailor to the solution input
def test_challenge_int():
# Use 0 or 1
# Use upper and lower limits
assert solution(2) == 2
assert solution(4) == 4
assert solution(0) == 0
assert s... |
class Node:
def __init__(self,v):
self.value = v
self.left = None
self.right = None
def insert(self,d):
if self.value == d: # Eru þessi gögn þegar fyrir
return False
elif self.value > d: # Förum vinstra megin
if ... |
"""
A colection of methods to sample examples from datasets
"""
import numpy as np
def get_first_examples(prop, m, classes, y, shuffle_function):
"""
Selects a sample of size prop*m, with two constraints:
(1) there must be at least one example from each class
(2) the distribution of classes in the sample is the s... |
#!/usr/bin/env python3
ipv4_addr = input("Please enter an IPv4 IP address: ")
print("You told me the IPv4 address is: " + ipv4_addr)
vendor_name = input("Enter the vendor name: ")
print("Your vendor name is: " vendor_name)
|
import math
import sys
''' *****************************************
# def startGame()
#
# Gives the start command on wheather the player
# will play the game or not
#
# Author : David Castellanos-Bentio
***************************************** '''
def startGame():
# Gives the start coordinates of th... |
"""
目标分析:有一组全球星巴克店铺的统计数据,如果想知道美国星巴克的数量狂和中国的哪个多,或者我们想知道
中国每个省份星巴克的数量的情况,那么我们应该怎么办?
"""
import pandas as pd
import numpy as np
directory = pd.read_csv("./directory.csv")
# 显示所有的行和列的详细信息,不会有省略号
pd.set_option('display.max_columns', None)
# pd.set_option('display.max_rows', None)
print(directory.head(1))
pr... |
"""
Practice Problem 4
The next Palindrome
a palindrome is a string which when reversed is eqal to itself
Ex of Palindrome 616,mom,676,1000001
Problem - You have to take a number as a input from the user.you have to find
the next palindrome corresponding .Your first input should be number of cases and then takes all t... |
#project Decoder
def decoder(input_str):
decoder = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5,
'f': 6,
'g': 7,
'h': 8,
'i': 9,
'j': 10,
'k': 11,
'l': 12,
'm': 13,
'n': 14,
'o': 15,
'p': 16,
... |
# Definición
# Abstracción
# Encapsulamiento
# Herencia
# Polimorfismo
class Animal:
# Atributos (cosas que tiene o que es)
patas = 4
color = "Verde"
sonido = ""
altura = 1.0
gusta_de = "contradecir"
# Cosas que hace
def correr(self):
print("Estoy corriendo con\
mis... |
# Punto de Terminción
# [1 , 2 , 3 ,4, 6]
# elem_0 + suma del resto
# primer
# suma de una lista de un elmento es el elemento mismo
def suma(lista):
if lista:
return lista[0] + suma(lista[1:])
else:
return 0
print(suma([1, 2, 3, 4]))
|
def even_odd(number):
"""Returns whether a number even or odd."""
if number % 2 == 0:
return 'even'
else:
return 'odd'
def birthday(name, age):
return "Happy birthday {}! I hear you're {} today.".format(name, age)
def display(message):
return message
def give_me... |
import os
from typing import Iterator
class Traverse(object):
@staticmethod
def traverse(base_path) -> Iterator[str]:
for root, _, fs in os.walk(base_path):
for f in fs:
if f.endswith('docx') or f.endswith('pdf') or f.endswith('txt'):
fullname = os.path... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def plot_missing(missing_stats):
"""Histogram of missing value for every features"""
plt.style.use('seaborn-white')
plt.figure(figsize=(7, 5))
plt.hist(missing_stats['missing_fraction'], bins=np.linspace(0, 1, 11), ... |
#ismail Enes KIRLI 16401728 ödev01
import sys
tuple_list={}
for i in range(int(sys.argv[1])):
x=input("ID, isim, soyisim ve yaş giriniz")
user=x.split()
ID= user[0]
isim= user[1:-2][0]
soyisim=user[-2]
yas=user[-1]
stringAd="".join(isim)
if ID.isdigit() and stringAd.isalp... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 24 16:01:27 2021
@author: pc
"""
def buildPartialSumArray(a,s,T):
s.append(a[0])
for i in range(1,T):
print("i : ",i)
print("i-1 : ",i-1)
temp=s[i-1]+a[i]
print("temp: ",temp)
s.append(temp)
return s
#Number of inp... |
dict1 = {
"imie" : "Dawid",
"nazwisko" : "Piotrowski",
"wiek" : 15,
"pesel" : "123456789",
"numer_telefonu" : "669254564"
}
print("Długość słownika: ", len(dict1))
print("\nKlucze słownika:\n")
for key in dict1:
print(key)
print("\nWartości słownika:\n")
for key in dict1:
print(dict1[key])
... |
import turtle
import keyboard
t = turtle.Turtle()
t.speed("fastest")
def equilateral_triangle(a):
for i in range(3):
t.forward(a)
t.left(120)
equilateral_triangle(50)
keyboard.wait("e") |
# Importando as bibliotecas Opencv(cv2) e numpy(nomeada como np)
import cv2
import numpy as np
# Antes de editar faça uma cópia(fork) desse repositório em sua conta
# Todas os exemplos das representações dos 7 tipos de frisos vistos aqui estão presentes no pacote "exemploFrisos"
'''
Uso da Opencv no projeto:
imread
i... |
class Position:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return f'({self.x},{self.y})'
class Character:
number_of_alive_characters = 0
def __init__(self, _name='Postac'):
self.name = _name
self.HP = 100
self.position = Pos... |
def say_hello(first_name, last_name="", age=0):
print(f'Hi {first_name} {last_name}')
print(f'You have {age} years old')
say_hello('Kamil', 'Kalis', 21)
say_hello("Jan", age=30)
def polygon(a, b):
print(f"Polygon areay is {a * b}, and circumference is {a + b}")
return a * b, a + b
polygon(2, 2)
x... |
from cs50 import SQL
from sys import argv, exit
#check number of arguments
if len(argv) != 2:
print("Incorrect number of arguments given")
exit(1)
# Connect with student database
db = SQL("sqlite:///students.db")
# Save input as house variable
house = argv[1]
# Query the database
students = db.execute(("SEL... |
import numpy as np
import sympy
import matplotlib.pyplot as plt
from math import factorial
x=sympy.symbols('x')
y=sympy.Function('y')(x)
x0=0.25
y0=1
h=0.01
yl=[] #лист со значениями 1й и 2й производной
x_x=[x0] #лист для отрисовки(x)
y_y=[] #лист для отрисовки(y)
def Sympy(f,x_x,y_y):
f=sympy... |
from cs50 import get_float
change = get_float("Change owed: ")
while change < 0:
change = get_float("Change owed: ")
count = 0
cent = change * 100
while cent>=25:
cent = cent - 25
count += 1
while cent>=10:
cent = cent - 10
count += 1
while cent>=5:
cent = cent - 5
cou... |
# A simple function that adds two numbers
def addNumbers (x, y):
return x + y
result = addNumbers(5,6)
print(result)
def intersect (seq1, seq2):
res = []
for x in seq1:
if x in seq2:
res.append(x)
return res
s1 = [1,2,3,4,5]
s2 = [4,5,6,7,8]
print(intersect(s1,s2))
#the global ... |
def tip():
def input_bill():
bill = int(input("Your bill gentelman, the total is about "))
perc = int(input("How much tip you want to pleasure me ? "))
people = int(input("How many gentelman you are her ? "))
return bill, perc, perc/100*bill, perc/100*bill + bill, people
def mai... |
import pygame
class Sprite(object):
def __init__(self, game, graphic):
self.__game = game
self.__graphic = graphic
self.__position = (0,0)
@property
def sprite(self):
return self.__graphic
@sprite.setter
def sprite(self, value):
self.__graphic = value
... |
import textwrap
def parse_script_args(args):
"""
Separate the command line arguments into arguments for pip
and arguments to Python.
>>> parse_script_args(['foo', '--', 'bar'])
(['foo'], ['bar'])
>>> parse_script_args(['foo', 'bar'])
(['foo', 'bar'], [])
"""
try:
pivot = ... |
import os
import pathlib
import traceback
from typing import List
def find_pdfs(f: pathlib.Path, pdfs: List[pathlib.Path] = []) -> List[pathlib.Path]:
"""Search a folder hierarchy and return a list of PDFs.
Symlinks are not searched.
Parameters
----------
f : str
The path to the folder to... |
#整个list翻转,再分别翻转两部分
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
nums.reverse()
def reverse(a,start,end):
while(start<end):
a[start],a[end]=a[end],a[start]
... |
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
if(len(flowerbed)==1):
if(flowerbed[0]==0 and n<=1):
return True
elif(flowerbed[0]==1 and n==0):
return True
else:
return False
... |
#用append做的很慢,memory占用也很高
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
result=[]
if(numRows==0):
return []
elif(numRows==1):
return [[1]]
elif(numRows==2):
return [[1],[1,1]]
for i in range(numRows):
... |
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
if(nums[0]>target):
return 0
elif(nums[-1]<target):
return len(nums)
for i in range(len(nums)):
if(nums[i]==target or (nums[i]>target)):
result=i
... |
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dic=collections.defaultdict(list)
for word in strs:
dic[tuple(sorted(word))].append(word)
return dic.values()
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
... |
class Solution:
def heightChecker(self, heights: List[int]) -> int:
temp=sorted(heights)
res=0
for i in range(len(heights)):
if(heights[i]!=temp[i]):
res+=1
return res
|
#这个短的可以出来,长的超时了
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if(nums[i]==nums[j] and j-i<=k):
return True
return False
#特别慢,memory还高
import nump... |
#recursion
class Solution:
def fib(self, N: int) -> int:
if(N==0 or N==1):
return N
return self.fib(N-1)+self.fib(N-2)
#循环,效率更高
class Solution:
def fib(self, N: int) -> int:
if(N==0 or N==1):
return N
elif(N==2):
return 1... |
def prisma_triangular() :
base = input("Introduzca la base:")
altura = input("Introduzca la altura:")
lateral1 = input("Introduzca la longitud del lateral 1")
lateral2 = input("Introduzaca la longitud del lateral 2")
piso = input("Introduzaca la longitud del piso")
altura = input("Introduzaca... |
import unicodedata
def format_phone_number(phone):
if phone is None or phone.strip() == '':
return ''
else:
"""
return '-'.join((phone[:3], phone[3:6], phone[6:]))
"""
return '(' + phone[:3] + ') ' + phone[3:6] + '-' + phone[6:]
def normalize(string):
return unicode... |
'''
Coded by Matthew Alves
Set up dictionaries
*Dictionaries are powerful in that they are mutable, dynamic, and can be nested
-> you can even map a list to a key which is what is done in this program
The dictionaries in this assignment emulate a database
The key in a dictionary is synonymous with a primary key in a... |
import random
import math
def calculate(attempts):
assert isinstance(attempts, int), 'you must provide an integer'
assert attempts > 0, 'you must provide a positive integer'
falling_inside = 0
for _ in range(attempts):
x = random.uniform(0.0, 1.0)
y = random.uniform(0.0, 1.0)
... |
import re
regex = re.compile(r'[0-9]{1,3}')
match = regex.match(text)
all_matches = match.groups()
print(match, all_matches)
match = regex.search(text)
all_matches = match.groups()
print(match, all_matches)
replace = regex.sub(replacement, text)
|
f=1
n=int(input('input n:'))
for i in range(n):
i+=1
f*=i
print('{} факториалы:'.format(n),f) |
##s = 'I am a student! I live in Almaty. This is my Unversity-KazNU!'
##sB = s.split('.')
##print(sB)
##
##for i in sB:
## print(i)
##s_s = []
##for i in sB:
## s_i = i.split('!')
## s_s.append(s_i)
##print(s_s)
##
##s_s1 = []
##for i in sB:
## if '!' not in i:
## s_s1.append(i)
## else:
## ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 13 10:34:30 2019
@author: Mannawar Hussain
"""
#linear search on unsorted list
def linear_search (L,e):
found = False
for i in range (len(L)):
if e == L[i]:
found = True
return found
#linear search on sorted list
def s... |
from PIL import Image, ImageDraw, ImageFont
import sys
XSIZE = 128
YSIZE = 128
# 与えた画像を、グレースケールのリストに変換する関数(白=1、灰=0.5、黒=0)
# 元がカラー画像でも対応出来るようにしている
def img2graylist(input_img):
#幅と高さを取得する
img_width, img_height = input_img.size
print('幅 : ', img_width)
print('高さ: ', img_height)
#最終的に出力する二次元リスト
result_grayli... |
import random
def makeList(num): #Converting a number to a list of digits
guess=[]
while num>0:
n=num%10
guess.insert(0,n)
num=int(num/10)
while len(guess) < 4:
guess.insert(0,0)
return guess
def printRules(): #Printing out the rules of the game
msg="\n\nThere is a secret 4 digit code, wit... |
"""
This program finds the "hourglasses" within a 2d array and calculates the highest
among them.
Hourglass Ex.
2 1 3
4
5 3 2
"""
import random
# Creates an array containing 6 lists, each of 6 items
w, h = 6, 6
arr = [[random.randrange(-9, 9) for x in range(w)] for y in range(h)]
#array to store Hourglass Sums
... |
def spiralTraverse(array):
spiralArray = []
leftBound = 0
topBound = 0
rightBound = len(array[0]) - 1
bottomBound = len(array) - 1
while bottomBound > topBound or rightBound > leftBound:
for i in range(leftBound, rightBound + 1):
print(array[topBound][i])
spiralArray.append(array[topBound][i])
to... |
# My attempt:
# Best: O(n) time | O(1) space
# Average: O(n^2) time | O(1) space
# Worst: O(n^2) time | O(1) space
def bubbleSort(array):
# iterate through whole array
for i in range(len(array)):
# iterate through whole array (minus last elem) until array[j] < array[j+1]
for j in ... |
"""input test"""
player = {
'HP': 100,
'attack': 100,
'defense': 100,
'name': 'Player 1'
}
enemy = {
'HP': 100,
'attack': 100,
'defense': 100,
'name': 'Player 1'
}
def update_name(entity):
print("enter a name for your entity")
new_name = input()
entity['name'] = new_name
return entity
update_name(pl... |
def solution(s):
answer = True
lst = list()
for i in range(len(s)):
lst.append(s[i])
while lst:
pre = lst.pop()
now = lst.pop()
print(pre, now)
return True
s = "((()))()"
print(solution(s))
|
# https://school.programmers.co.kr/learn/courses/30/lessons/43165
def solution(numbers, target):
answer = 0
listAnswer = [0]
for num in numbers:
tmp = []
for i in listAnswer:
tmp.append(i + num)
tmp.append(i - num)
print(tmp)
listAnswer = tmp
pr... |
#José Everton da Silva Filho
#AdS - P1 - Unifip - Patos/PB
#LISTA - 01
#---
#4 - Calcule a área de um retângulo (base x altura).
base = float(input('Digite o tamanho da base em centímetros: '))
altura = float(input('Digite o tamanho da altura em centímetros: '))
ret = base * altura
print('A área do retângulo é de {}cm.... |
# José Everton da Silva Filho
# Exercício 04 - AdS - P1 - Unifip - Patos/PB
#####
'''
4 - Faça um programa que lê as duas notas parciais obtidas por um aluno numa disciplina ao longo de um semestre,
e calcule a sua média. A atribuição de conceitos obedece à tabela abaixo:
Média de Aproveitamento Conceito
Entre 9.0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.