text stringlengths 37 1.41M |
|---|
def average():
score1 = float(input("input 10 score percentages"))
score2 = float(input(""))
score3 = float(input(""))
score4 = float(input(""))
score5 = float(input(""))
score6 = float(input(""))
score7 = float(input(""))
score8 = float(input(""))
score9 = float(input(""))
scor... |
# Hero's inventory
# Jacob Jensen
#11/18
import random
player_health = 100
player_armor = 1250
player_attack = 250
player_money = 0
inventory = ["rusty sword","leather armor","wood shield","small healing potion"]
player_stats = ["health",player_health,"armor",player_armor,"attack",player_attack,"money",player_money]... |
name1 = input("enter a name")
object2 = input("enter an object")
object3 = input("enter another object")
Species4 = input("enter a species real or fake")
action5 = input("enter an action")
print ("One day " + name1 + " was walking and found a " + object2 + " and a " + object3 + " that was picked up by a " + Species4 +... |
#two way if exe
#jacob jensen
#10/6/18
##num = int(input("enter a number"))
##
##if num%2 == 0:
## print("that number is even")
##else:
## print("that number is odd")
##
##print("the program is finished")
num1 = float(input("pick a number"))
num2 = float(input("pick a number"))
if num1<=num2:
if num1 == num... |
# Rock Paper Scissors
# (based on Alyssa Harris code from python tutorials)
#
# Coding Club 18 Jan 2018
#
# This program takes user choice of R P or S and plays it
# against a random choice of R P S by the computer
# and prints out who wins.
#
# updated on the fly during the session to have two user choices instead of
... |
import math
def factors_sum(n):
L = int(math.sqrt(n)+1)
ans = 0
for i in xrange(1, L, 1):
if n%i == 0:
ans += i
d = n/i
if d != i:
ans += d
return ans
def solve():
t = int(raw_input())
while t > 0:
t -= 1
n = int(raw_... |
fib = [0, 0, 1]
def fib_seq():
for i in range(3, 4784):
fib.append(fib[i-1]+fib[i-2])
def bsearch(num):
l = 0
h =len(fib)-1
while l <= h:
m = (l+h)/2
if fib[m] == num:
return m;
elif fib[m] < num:
l = m+1
else:
h = m-1
return -1
if __name__ == '__main__':
fib_seq()
t = int(raw_input())
whil... |
#took high temps from sitka alaska and plotted them using matplotlib
import csv
open_file = open("sitka_weather_07-2018_simple.csv", "r")
csv_file = csv.reader(open_file, delimiter= ",") #use the delimiter function
header_row = next(csv_file)
'''
print(header_row) #the next function skips reading the first line
fo... |
#!/usr/bin/env python
#Be sure the indentation is identical and also be sure the line above this is on the first line
import sys
import re
def main(argv):
line = sys.stdin.readline()
while line:
# split line by ','
parts = line.split(',')
# check to make sure this isn't the header row.. if it is the hea... |
#from math import *
from pylab import *
from sympy import diff
from sympy.abc import x
def newton(funcion, df, vi, TOL, N,vectorx,vectory):
i = 0
while i<N:
vectorx[i] = vi
x = vi
f = eval(funcion)
df_val = eval(df)
vectory[i] = f
if df_val == 0:
... |
#!/usr/bin/env python3
from sys import argv
G = 9.80665
x, v, t = float(argv[1]), float(argv[2]), float(argv[3])
output = x + v*t - .5*G*(t**2)
print(output)
|
#get the input string from user
print ("Enter a string in uppercase:")
string = input()
#convert to lowercase
output = string.lower()
#print the output
print ("Lowercase:")
print (output)
|
# Первый вариант:
# marka_dict = {
# 'Марка': marka,
# }
# model_dict = {
# 'Модель': model
# }
# year_dict = {
# 'Год выпуска': year
# }
# mashina_list = [marka_dict, model_dict, year_dict]
# print(mashina_list)
# mashina()
# Исправленный вариа... |
# Задание 1. Первый способ:
i = 700
while i // 7:
print(i)
i -= 7
#Второй способ (с range):
i = 0
while i in range(0,700,7):
print(i)
i += 7
# Задание 2.
name = input('Введите имена людей одинакового пола: ')
pol = input('Введите пол: (мужской/женский): ')
men = list()
women = list()
if p... |
# Lists are really variable
my_list = [(x, x**2) for x in range(1, 10)]
print(my_list)
"""
Single- or double-linked lists.
Single-linked lists references only to the next object.
Double-linked lists references both to the previous and the next object.
"""
|
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 27 2018
@author: Francesco
"""
# ELABORAZIONE DATI CSV
import pandas as pd
#import xlrd
DF1 = pd.read_excel("Domini_min.xlsx")
## print the column names
print(DF1.columns)
EXCEL_FILE = pd.ExcelFile("Domini_min.xlsx")
SHEET_NAMES = EXCEL_FILE.sheet_names
print(SHEET_... |
"""
How many days from yyyy mm dd until the next mm dd
Authors: yuanw
Credits: None
of this code, credit them here. You don't have to credit the course
instructor, GTFs, or tutors / helpers in office hours.
CIS 210 assignment 3, Winter 2014
Usage example: python days_till.py 2012 09 24 06 14
(first day of... |
#Write a program that returns a list that contains only the elements
#that are common between the lists (without duplicates). Make sure your
#program works on two lists of different sizes.
import random as rand
import time as t
rand.seed(t.gmtime())
a = []
b = []
c = []
for x in range(rand.randint(1,50)):
a.app... |
#Ask the user for a number. Depending on whether the number is even or odd,
#print out an appropriate message to the user.
number = int(input("Friend, give me a number: "))
if number % 2: ###Number is odd
print(str(number) + " is an odd number")
else:
print(str(number) + " is an even number")
|
"""
Simple computer vision application to show the use
of tensorboard using model.fit method
in iPython
"""
from datetime import datetime
import tensorflow as tf
from tensorflow import keras
import tensorflow_datasets as tfds
batch_size = 10
EPOCHS = 100
# load train
data, info = tfds.load('eurosat', split="train", w... |
import os
import requests
import time
def download_wiki_topic_page(topic_slug):
"""Download a topic's page given the topic slug.
Keyword arguments:
topic_slug -- the part of the wiki article relative URL after /wiki/
"""
output_file_path = 'data/article_' + topic_slug + '.html'
wiki_a... |
class InputOutputString(object):
def __init__(self):
self.s = ""
def getString(self):
self.s = input("Give a new string")
def printString(self):
print(self.s.upper())
|
"""
Keregessunk be pozitiv egesz szamokat addig, amig 0-t nem kapunk.
Ezutan irjuk ki, hogy melyik szam hanyszor szerepelt, egeszen a legnagyobb kapott szamig.
Pleda bemenet:
--------------------------------------------
1
1
2
1
5
0
--------------------------------------------
Pelda kimenet:
-------------------------... |
## Initializations
#Cat Locations
cat_1 = 1
cat_2 = 3
#haven't found 'em yet
found_cat_1 = false
found_cat_2 = false
# End initialization
#start game
print "welcome to cat game"
while !found_cat_1 and !found_cat_2
print "there are a bunch of rooms, pick one"
player_input = prompt(input)
#set location to the input
... |
#This string is talking about what kinds of people there are
x = "There are %d types of people." %10\
# This is a string for the first type of person
bianary = "bianary"
# this is the string for the second type of person
doNot = "don't"
# This string adds the two types together
y = "Those who know %s and those who know... |
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
values = np.array([9534092, 50541, 98755, 120705])
cnf_mat = values.reshape(2, 2)
print(cnf_mat)
#Code to generate heatmap given a confusion matrix
def heatMap(cnf_mat):
heat_map = sns.heatmap(cnf_mat, annot=True, cmap="YlGnBu", fmt='g')
... |
import pygame as pg
class Button(pg.sprite.Sprite):
"""
Class for buttons. They have some text on them, can change color.
Action is a function that needs to be called when button is clicked.
"""
def __init__(self, text, font, location, action):
pg.sprite.Sprite.__init__(self)
self.... |
# ----------
# User Instructions:
# https://youtu.be/bQA2ELDNmmg
# https://youtu.be/M7ZJ74RVHqo
#
# Implement the function optimum_policy2D below.
#
# You are given a car in grid with initial state
# init. Your task is to compute and return the car's
# optimal path to the position specified in goal;
# the costs for e... |
# 1. Power up Tello
# 2. Connect to Tello network
# 3. Run this script with Python
import cv2
import os
import time
from lib.tello import Tello
# Construct a Tello instance so we can communicate with it over UDP
tello = Tello()
# Send the command string to wake Tello up
tello.send("command")
# Delay
time.sleep(1)
... |
import time
import random
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard
screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
player = Player()
scoreboard = Scoreboard()
screen.listen()
screen.onkeypress(player.move_forward, "... |
# TODO: Create a letter using starting_letter.txt
with open("Input/Letters/starting_letter.txt") as letter_tem:
contents = letter_tem.read()
with open("Input/Names/invited_names.txt") as names:
for i in range(1, 9):
name = names.readline()
name = name.strip("\n")
lett... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 03:05:44 2021
@author: 王泓文
"""
#Day2 tips calculaion
print("Welcome to the calculator")
bill = input("How much is the total bill? $")
tips = input("How much percentage you want to give as tips? 10, 12 or 15?")
person = input("How many person will split this bill?")
ti... |
"""
2 -Crie uma função que receba como parâmetro uma lista,com valores de qualquer tipo.
A função deve imprimir todos os elementos da lista numerando-os.
"""
lista = [1, 2, 'a', 'b', 'c',20]
def enumera(l):
contador = 0
for x in l:
contador = contador + 1
print('{}º) {}'.format(contador,x))
... |
"""
Escreva um programa que categorize cada mensagem de
e-mail de acordo com o dia em que a mensagem foi enviada. Para
isso, procure por linhas que comecem com “From”, depois procure pela
terceira palavra e mantenha uma contagem de ocorrência para cada dia
da semana. No final do programa, mostre em tela o conteúdo do s... |
"""
Encapsule esse código em uma função chamada contagem,
e generalize para que ela aceite a string e a letra como argumentos.
"""
palavra = input("Digite uma palavra: ").strip().lower()
letter = input("A letra da palavra anterior a ser contada: ").strip().lower()
def contagem(letra,string):
contador = 0
for ... |
"""
Exercícios:funções
1 -Crie uma função para desenhar uma linha, usando o caractere'_'.
O tamanho da linha deve ser definido na chamada da função.
"""
def linha(n):
for i in range(n):
print (end='_')
print(" ")
l = int(input("Digite o tamanho da linha: "))
linha(l) |
import sqlite3
from urllib.parse import urlparse
from termcolor import colored
from spider import spider_website
def create_tables():
cur.executescript('''
CREATE TABLE IF NOT EXISTS Websites (
website_url TEXT UNIQUE
);
CREATE TABLE IF NOT EXISTS Pages (
id INTEG... |
import collections
Location = collections.namedtuple('Location', 'row column')
Shape = collections.namedtuple('Shape', 'width height')
class GameBoard:
"""
Class to create and manipulate the boards of the game.
"""
def __init__(self, myShape):
"""
Initialization of the board with ... |
from enum import Enum
class TileType(Enum):
FLOOR = 1
WALL = 2
class Tile:
def __init__(self, tile_type, coords):
self.type = tile_type
self.game_objects = []
self.coords = coords
def __str__(self):
if self.type is TileType.FLOOR:
return "F"
else:... |
'''
Користувач вводить рядок, що містить римський запис числа. Напишіть функцію, що повертає це число у арабському записі. Виведіть результат.
У випадку помилкового вводу виведіть повідомлення про помилку.
(Римські позначення цифр: M=1000, D=500, C=100, L=50, X=10, V=5, I=1. Жоден символ не може повторюватися понад 3 р... |
"""Functions to aid in quick maths to calculate for ad-hoc analysis and feature engineering."""
from typing import Optional
import pandas as pd
from wsbtrading import check_columns
def divide_kernel(numerator: float, denominator: float) -> float:
"""Divides one number by another number.
Args:
numera... |
""" Pancake """
def main():
""" input """
num1 = int(input())
num2 = int(input())
num3 = int(input())
num4 = 0
num5 = 0
num6 = 0
total = 0
if num1 > num3:
print("Pay: %d"%(num3*20))
while num6 < num3:
num6 += 1
print("Get: %d"%(num6))... |
# coding: utf-8
import gym
from gym import spaces
import random
from game2048 import Game2048
import numpy as np
class Game2048Env(gym.Env):
"""
Description:
A pole is attached by an un-actuated joint to a cart, which moves along a frictionless track. The pendulum starts upright, and the goal is to pr... |
# Password generator that includes letters, punctuations and digits as well as
# an error handler for invalid input
import string, random
characters = string.ascii_letters + string.punctuation + string.digits
password = ''
while True:
try:
number_of_characters = int(input("How many characters w... |
import wikipedia as wiki
from tkinter import *
from wikipedia.wikipedia import search
## Estrutura da API
wiki.set_lang("pt")
#print(wikipedia.search("Bebeto"))
########################################################################################
## Janela TKinter
Application = Tk()
Application.title('PCA... |
""" math_master DOCSTRING 1.0"""
import time
class Factorial:
""" math_master DOCSTRING 1.0"""
n = 0
def __init__(self, n):
""" math_master DOCSTRING 1.0"""
assert isinstance(n, int), "In factorial(n) n shoud be a int ;)"
self.n = n
def calculate(self):
""" math_master D... |
import random
class Quizmaster:
def __init__(self, min_range, max_range):
self.min_range = min_range
self.max_range = max_range
self.left_operand = 0
self.right_operand = 0
self.answer = 0;
self.in_progress = False
def get_plus_question(self):
self.l... |
# while loop
user_input = input('Enter q or p: ')
# Now we must repeat until they type 'q':
while user_input != 'q':
# Inside our loop, check if they typed 'p'. If they did, print "Hello"
if user_input == 'p':
print("Hello : "+user_input)
# Now we must ask the user for their input again—otherwise ... |
def starts_with_m(friend):
return friend.startswith('M')
friends = ['Mukesh', 'Nikki','Saurabh','Nikhil','Pradeep', "Raphael", 'Mats']
start_with_m = filter(starts_with_m, friends)
print(next(start_with_m))
print(next(start_with_m))
|
a=input()
b=a[ ::-1]
if(b==a):
print("YES")
else:
print("NO")
|
a=int(input())
if((a%4)==0 and (a%100)!=0):
print("yes")
else:
print("no")
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def recoverTree(self, root: TreeNode) -> None:
pre, first, second = [None], [], []
def inorde... |
# Iterative O(n)
def find_min_and_max(array: list) -> list:
min_number = float('inf')
max_number = float('-inf')
for each in array:
min_number = min(min_number, each)
max_number = max(max_number, each)
min_and_max = [min_number, max_number]
return min_and_max
def find_min_max_r... |
'''
Created on Apr 18, 2019
@author: s271486
'''
# Created by: Mr. Coxall
# Created on: Nov 2017
# Created for: ICS3U
# This program is an example of a structure
class Student():
def __init__(self, first_name, last_name, grade):
self.first_name = first_name
self.last_name = last_name
... |
#!/usr/bin/python
import argparse, sys, re
parser = argparse.ArgumentParser(description="Program to solve Advent of Code for 2016-12-08")
parser.add_argument("--input_file", default="input.txt")
parser.add_argument("--width", default=50, type=int)
parser.add_argument("--height", default=6, type=int)
args = parser.par... |
#!/usr/bin/python
import argparse, sys
parser = argparse.ArgumentParser(description="Program to solve Advent of Code for 2016-12-04")
parser.add_argument("input_file")
args = parser.parse_args()
def decrypt_name(room):
shifts = int(room["number"]) % 26
newwords = []
for word in room["letters"].split("-... |
#A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
#Not a great ON, but necessarily hits the answer relatively early.
def Palindrome(num):
if str(num) == str(n... |
'''
两个字符串 s 和 t,判断它们是否是同构
eg:
s = "egg", t = "add" => True
s = "foo", t = "bar" => False
s = "paper", t = "title" => True
s = "ab", t = "ab" => True
s = "ab", t = "aa" => False
s = "ba", t = "aa" => False
Given two strings s and t, determine if... |
'''
字符串s & t ,判断 t 是否是 s 的字母异位词
eg:
s = "anagram", t = "nagaram" => true
s = "rat", t = "car" => false
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
```
Input: s = "anagram", t = "nagaram"
Output: true
```
Example 2:
```
Input: s = "rat", t = "car... |
'''
求2个数组的公共元素,以数组形式返回(不去重)
eg:
[1,2,2,1], [2,2] => [2,2]
[4,9,5], [9,4,9,8,4] => [4,9]
Given two arrays, write a function to compute their intersection.
Example 1:
```
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
```
Example 2:
```
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9... |
def _shiftRightByOne(C, a, b):
"""Shifts all elements in the range [a, b) to the right by one.
Causes out-of-bounds error if range is nonempty (a < b) and b >= len(C)."""
i = b-1
while i >= a:
x = C[i]
C[i+1] = x
i -= 1
def insertion_sort(A):
"""Sorts the list A in place"""
i = 1
... |
import math
# ---- Problem 1 ----
class Line():
def __init__(self,coor1,coor2):
self.coor1 = coor1
self.coor2 = coor2
self.x = coor2[0] - coor1[0]
self.y = coor2[1] - coor1[1]
def distance(self):
return math.sqrt((self.x ** 2) + (self.y ** 2))
def slope(... |
from turtle import Turtle
import random
class Food(Turtle):
def __init__(self):
super().__init__()
self.shape("circle")
self.penup()
self.shapesize(stretch_len=0.5, stretch_wid=0.5)
self.color("blue")
self.speed("fastest")
self.refresh_food_position()
... |
import turtle
from turtle import Turtle
import random
turtle.colormode(255)
turtle.speed("fastest")
tortu = Turtle()
def generate_random_color():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return (r, g, b)
for degree in range(0,360, 2):
tortu.color(generate_... |
import turtle
from turtle import Turtle
import pandas
# Variables
total_adivinadas = 0
# Logica de la pantalla
screen = turtle.Screen()
screen.title("Juego de Povincias del Ecuador")
image = "Ecuador_mapa.gif"
screen.addshape(image)
turtle.shape(image)
# Logica de los datos
row_data = pandas.read_csv("provincias.csv... |
#Abigail Lowe
#Decimal-binary, Binary-Decimal, Decimal-Hexadecimal conversion program
#COSC 101
ans=True
while ans:
print("""
1.Decimal to Binary Conversion
2.Binary to Decimal Conversion
3.Decimal to Hexadecimal Conversion
4.Exit/Quit [ends program]
""")
ans=input("Select desire... |
from tkinter import *
def btnclick(nums):
global operator
operator = operator + str(nums)
text_input.set(operator)
# This function will allow users to click on a button and it will display that on screen of calculator.
# text_input is a variable being used to print values on calculator screen(se... |
import random
def display_board(board):
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' ... |
import heapq
class PriorityQueue(object):
def __init__(self, content=None):
if content is None:
content = []
self.heap = content
if self.heap:
self.update()
def __iter__(self):
return self
def __next__(self):
return self.next()
def next... |
# Creating and accessing tuples.
# retrieve hour, minute and second from user
hour = int( input( "Enter hour " ) )
minute = int( input( "Enter minute " ) )
second = int( input( "Enter second " ) )
currentTime = hour, minute, second # create tuple
print ("The value of currentTime is:", currentTime)
# access tuple
print... |
values=[]
print("Enter 10 integers")
for i in range(10):
newValue = int(input("Enter integer %d : " % (i + 1)))
values += [newValue]
print(values)
print ("\nCreating a histogram from values:" )
print ("%s %10s %10s" % ( "Element", "Value", "Histogram" ) )
for i in range( len( values ) ):
print ("%7d %10d... |
import re
txt = "pavithra ramamoorthy 1997"
x = re.search("^pavi.*thy$", txt)
if (x):
print("YES! We have a match!")
else:
print("No match")
#findall
#set of characters
x=re.findall("[a-m]",txt)
print(x)
#any character
x=re.findall("pa.....a",txt)
print(x)
#does not contain digits
x=re.find... |
def append_middle(s1, s2):
middle_index = int(len(s1) /2)
print("Original Strings are", s1, s2)
middle_three = s1[:middle_index-1:]+ s2 +s1[middle_index-1:]
print("After appending new string in middle", middle_three)
append_middle("pavithra", "pavithraramamoorthy") |
# import modules
FILE_NAME = 'fdic_failed_bank_list.csv'
# write a function to output the first row of a csv file
# and get the column names
# open the csv
# create the object that represents the data in the csv file
# create a variable to represent the header row
# output the value
# output ... |
# import modules
import csv
FILE_NAME = 'fdic_failed_bank_list.csv'
# write a function to open a csv file
def open_csv_file(file_name):
# open the csv
csv_file = open(file_name, 'rb')
# create the object that represents the data in the csv file
csv_data = csv.reader(csv_file)
# output that obje... |
# import modules
FILE_NAME = 'fdic_failed_bank_list.csv'
# write a function to do some exploring with integers
# open the csv
# create the object that represents the data in the csv file
# create a variable to represent the header row
# let's get the first row of data
# let's create a varaibl... |
# import modules
import csv
# write a function to open a csv file
def open_csv_file(file_name):
# open the csv
csv_file = open(file_name, 'rb')
# create the object that represents the data in the csv file
csv_data = csv.reader(csv_file)
# output that object to the terminal
print csv_data
... |
#1/usr/bin/pyton
#-*- coding: utf-8 -*-
a = input("Cien, liet.,lūdzu, ievadi skaitli")
#3. python'ā visi input rezultāti ir ar str datu tipu
# tāpēc ievadītā lieluma datu tips vēlāk ir jāpārveido
a = int(a)
# python valoda balstās uz C valodas -> print strādā līdzōgi printf
# https://www.cplusplus.com/referemce/cstdio/... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from chess_configurations.solver import backtracking
from chess_configurations.models import Board, King, Rook, Knight
def test_very_simple():
"""
A board with one position available.
test_very_simple_1x1_board_with_one_piece
"""
e... |
# Given the root to a binary tree, implement serialize(root), which serializes the tree into a string,
# and deserialize(s), which deserializes the string back into the tree.
#
# For example, given the following Node class
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
... |
# Problem Description:
#
# A unival tree (which stands for "universal value") is a tree where all
# nodes under it have the same value.
#
# Given the root to a binary tree, count the number of unival subtrees.
# For example, the following tree has 5 unival subtrees:
# 0
# / \
# 1 0
# / \
# 1 0
# / \
# 1... |
class ShoppingCart:
def __init__(self):
self.__total = 0
self.items = {}
def add_item(self, item_name, quantity, price):
self.__total += quantity * price
self.items[item_name] = quantity
def remove_item(self, item_name, quantity, price):
if item_name not in self.ite... |
# The program is to ask the user to enter his name and say hello.
name = input("Please Enter Your Name >> ")
print("Hello %s !! We Are Happy To Welcome You. " %name)
|
# Programación Orientada a Objetos con Python3
import datetime
class Employee:
nums_of_emps = 0
raise_amount = 1.04
def __init__(self, first, last, pay):
''' Employee constructor '''
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last... |
# Dictionary
""""
1.A dictionary is a collection which is unordered, changeable and indexed.
2.In Python dictionaries are written with curly {} brackets, and they have keys and values.
3.Accessing Items: You can access the items of a dictionary by referring to its key name, inside square [] brackets.
4.Accessing I... |
# Absolute Function
"""
The abs() method returns the absolute value of x i.e.
the positive DISTANCE between x/-x and zero.
"""
x = 10
print(abs(x))
y = -10
print(abs(y))
|
from datetime import date, timedelta
days = dict()
for i in range(1, 7):
day_name = 'day_{}'.format(i)
day = date.today()-timedelta(days=(i-1))
days[day_name] = day
days2 = {y:x for x,y in days.items()}
print(days) |
odd_set = set()
even_set = set()
for number in range(10):
if number % 2:
odd_set.add(number)
else:
even_set.add(number)
print("odd set: " + str(odd_set))
print("even set: " + str(even_set))
union_set = odd_set | even_set
print("union_set: " + str(union_set))
union_set = odd_set.union(even_se... |
import sys
import unicodedata
def print_unicode_table(word):
print("decimal hex chr {0:^40}".format("name")) # align by center for {0} - name
print("------- ----- --- {0:-<40}".format("")) # align left
code = ord(" ") # return an integer representing the Unicode code point of character
end =... |
#Fucntion to find the maximum repeated character
def d_find_repeated(d_sequence):
max_occurence=0
d_repeated_list=[]
d_unique=set(d_sequence)
for i in d_unique:
if d_sequence.count(i)>=max_occurence:
max_occurence=d_sequence.count(i)
d_repeated_list.append(i)
... |
"""Find the number of paths of a binary tree that sum to a given value."""
from collections import deque
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solut... |
#!/usr/bin/env python
# encoding:UTF-8
"""
Implement the following routine:
Integer findg(Integer, Integer∗)
such that findg(p,f) will return a generator of Z∗p where p is a prime
and f is a list of the prime factors of p−1.
"""
wiki primitive root modulo n
|
#!/usr/bin/env python3
import unittest
from gameOfLife import Board
class TestGOFBoard(unittest.TestCase):
def setUp(self):
self.board = Board(6,6, random_init=False)
def test_countNeighbour0(self):
self.assertEqual(self.board._countNeighbour(1,1) , 0)
def test_countNeighbour1(self):... |
from enum import IntEnum
__all__ = ["validate_roman_numeral", "roman2int", "int2roman"]
class RomanNumeral(IntEnum):
I = 1
V = 5
X = 10
L = 50
C = 100
D = 500
M = 1000
def validate_roman_numeral(numeral):
return all(char.upper() in RomanNumeral.__members__ for char in numeral)
def... |
import random
random_num = random.random()
# the random function will return a floating point number, that is 0.0 <= random_num < 1.0
#or use...
random_num = random.randint(60,100)
print random_num
def grade_test(score):
if score >= 90:
print "Score:",score,"; Your grade is A"
elif score >= 80:
... |
#!/usr/bin/env python
import urllib2
def get_text():
url = 'https://raw.githubusercontent.com/javimb/intro-python/master/exercises/exercise_2/trash.txt'
return urllib2.urlopen(url).read()
# EXERCISE 2
# Obtener la suma de los numeros
text = get_text()
nums = filter(lambda num: num in '0123456789', text)
in... |
def word_count(word):
words = word.split()
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
return counts
print(word_count('testing 1 2 testing'))
|
# -*- coding: utf-8 -*-
"""
Next Permutation
================
Implement the next permutation, which rearranges numbers into the numerically next greater permutation of numbers.
If such arrangement is not possible, it must be rearranged as the lowest possible order ie, sorted in an ascending order.
The replacement mu... |
"""
Merge Intervals
===============
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9] insert and merge [2,5] would result in [1,5],[6,... |
"""
Window String
=============
Given a string S and a string T, find the minimum window in S which will contain
all the characters in T in linear time complexity.
Note that when the count of a character C in T is N,
then the count of C in minimum window in S should be at least N.
Example :
S = "ADOBECODEBANC"
T = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.