text stringlengths 37 1.41M |
|---|
#Useful Binary Search template that can solve most problem.
def template(searchArray):
#base case:
if not searchArray:
return None
#Condition requirement: these are varies depends on the problem and it is up to the user to find the pattern
def condition(searchArray):
#add code here:
pass
left = 0
rig... |
if __name__ == '__main__':
a = int(input())
b = int(input())
if (a > 0 and b > 0):
print(a + b)
print(a - b)
print(a * b) |
"""
Created by Daniel Susman (dansusman)
Date: 10/03/2020
This module holds the InsertionSort class, which holds all of the functionality required
to display the sorting of a given array using the Insertion Sort algorithm.
"""
from algorithms import Algo
class InsertionSort(Algo):
""" Represents the Insertion So... |
#Carlos Ochoa
#Calcula el total a pagar por unos asientos determinando el tipo de asiento
#Calcula el pago total de los asientos
def calcularPago(asientosA, asientosB, asientosC):
pagoA=asientosA*870
pagoB=asientosB*650
pagoC=asientosC*235
totalPago=pagoA+pagoB+pagoC
return totalPago
def main(... |
"""Word Finder: finds random words from a dictionary."""
import random
class WordFinder:
...
def __init__(self, path):
self.words = open(path, "r")
print(f"{self.words_read()} words read")
def words_read(self):
count = 0
for line in self.words:
... |
def weight_on_planets():
weightEarth = int(input("What do you weigh on earth? "))
weightMars = weightEarth * 0.38
weightJupiter = weightEarth * 2.34
print("\nOn Mars you would weigh", weightMars, "pounds.")
print("On Jupiter you would weigh", weightJupiter, "pounds.")
return
if __name_... |
class WordDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = {
'isEnd': True,
'neighbors': {}
}
def addWord(self, word):
"""
Inserts a word into the trie.
:type wo... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
... |
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
if len(p) == 0:
return len(s) == 0
if p[1] == '*':
return (self.isMatch(s, p[2:]) or len(s) != 0 and (s[0] == p[0] or '.' == p[0]) and self... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
left_h = lef... |
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i = j = 0
for k in range(len(nums)):
v = nums[k]
nums[k] = 2
if v < 2:
... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:r... |
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
self.zeroDict = {}
rows = len(board)
if rows > 0:
cols = len(board[0])
else:
... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
lh = self.height(root)... |
# Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
def __str__(self):
return '[' + str(self.start) + ',' + str(self.end) + ']'
class Solution(object):
def merge(self, intervals):
"""
:type intervals: L... |
import unicodedata
class NormalizedStr:
'''
By default, Python's str type stores
any valid unicode string.
This can result in unintuitive behavior.
For example:
>>> 'César' in 'César Chávez'
True
>>> 'César' in 'César Chávez'
False
The two strings to the right of the in
... |
# -*- coding: utf-8 -*-
'''
Universidade Federal de Pernambuco (UFPE) (http://www.ufpe.br)
Centro de Informática (CIn) (http://www.cin.ufpe.br)
Graduando em Sistemas de Informação
IF969 - Algoritmos e estrutura de dados
Autor: Emerson Victor Ferreira da Luz (evfl)
Email: evfl@cin.ufpe.br
Data: 2017-10-22
Copyrigh... |
# insert an image into the database.
import sqlite3
# connect to the already existing database
db = sqlite3.connect('images.sqlite')
db.execute('DROP TABLE image_store')
db.commit()
db.execute('CREATE TABLE image_store (i INTEGER PRIMARY KEY, image BLOB, filetype TEXT, imgName TEXT, imgDesc TEXT)')
db.commit()
# con... |
def min_max(minmax, num):
if minmax[0] is None:
minmax[0] = num
minmax[1] = num
else:
if num > minmax[1]:
minmax[1] = num
if num < minmax[0]:
minmax[0] = num
return minmax
def main():
string = input()
num1 = ""
num2 = ""
... |
def is_prime(n, range_div):
count = 0
if (n > 10) and (n % 10 == 5):
count = 1
else:
i = 0
while range_div and n >= range_div[i] * range_div[i]:
if n % range_div[i] == 0:
count = 1
break
i += 1
return False if c... |
def main():
x = float(input())
y = float(input())
print("NO") if x > 1 or x < -1 or y > 1 or y < -1 else print("YES")
# start program
main() |
#!/usr/bin/env python
__author__ = 'Alex Chung'
__email__ = 'achung@ischool.berkeley.edu'
__python_version__="2.7"
"""
Game Rules:
In the game of Ghost, two players take turns building up an English word from left to right.
Each player adds one letter per turn. The goal is to not complete the spelling of a word:
i... |
from tkinter import *
app=Tk()
text=Text(app,undo=True,autoseparator=False)
text.pack()
text.insert(1.0,'I trust fishc.com')
'待注释'
def callback(event):
text.edit_separator()
text.bind('<Key>',callback)
'定义撤销方法,添加撤销按钮'
def show():
text.edit_undo()
Button(app,text='撤销',command=show).pack()
mainloop() |
print()
'''
属性:姓名(默认姓名为’小甲鱼‘)
方法:打印姓名
方法中对属性的引用形式需要加上self.如:self.name
'''
class Person:
name='小甲鱼'
def printName(self):
print('我的名字叫:%s'%self.name)
person=Person()
person.printName() |
'''
1 定义一个单词(word)类继承自字符串,重写比较操作符的,当两个word类对象进行比较时,
根据单词的长度来进行比较大小。
加分要求:实例化如果传入的是带空格的字符串,则取第一个空格前的单词作为参数
'''
class Word(int):
def __new__(cls, args):
if isinstance(args,str):
if ' 'in args:
length=args.find(' ')
else:
length = len(args)
a... |
import random
class Turtle:
moveStep=random.randint(1,2)
movedirection=0
min_x=0
max_x=10
min_y=0
max_y=10
position=[0,0]
hp=1005
#随机生成乌龟的移动方向
def getDirection(self):
self.movedirection=random.randint(-1,1)
if self.movedirection==-1:
print('乌龟决定往回游,移... |
class Celsius:
def __init__(self,value=26.0):
self.value=float(value)
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
self.value=value
class Fahrenheit:
def __get__(self, instance, owner):
return instance.cel*1.8+32
def __... |
import math
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
class Line:
def getlen(self,Point,Point2):
result=math.sqrt((Point.x-Point2.x)**2+(Point.y-Point2.y)**2)
return result
pointA=Point(1,0)
pointB=Point(2,0)
line=Line()
print(line.getlen(pointA,pointB)) |
print()
'''
1 写一个函数get_digits(n),将参数n分解出每个位的数字并按顺序存放在列表中。
如:get_digits(12345)——[1,2,3,4,5]
'''
result = []
def get_digits(n):
if n > 0:
result.insert(0, n % 10)
get_digits(n // 10)
'这里只是控制了执行的次数而已,每次的结果直接放在了外面的全局变量'
'假如放在里面的话会重复的初始化,导致拿不到完整的列表'
get_digits(12345)
print(result)
'普... |
def compare(file1,file2):
file_content1=open(file1)
file_content2=open(file2)
count=0
differ = []
for i in file_content1:
j=file_content2.readline()
count+=1
if i!=j:
differ.append(count)
file_content1.close()
file_content2.close()
return differ
fi... |
tmp=input("请输入你的成绩:")
while not tmp.isdigit():
tmp=input('你的输入有误!请重新输入:')
score=int(tmp)
if 60<=score<80:
print("C")
elif 60<=score<70:
print("D")
elif 0<=score<60:
print("F")
elif 80<=score<90:
print("B")
elif 90<=score<=100:
print("A")
else:
print('非法成绩') |
'过滤字符串对于求和的影响'
def sum(x):
result=0
for i in x:
if type(i)==float or type(i)==int:
result=result+i
else:
continue
return result
print(sum([1,2,4,5,6,3.15,7.25,'sdfdsf',10*10])) |
#for循环方法
a=1
for i in range(0,101):
if i%2!=0:
print(i,end=' ')
#换行打印
print('')
while a<=100:
if a % 2!=0:
print(a,end=' ')
a+=1
|
def huiwenlian():
'''回文联是指顺着读跟倒着读文字显示的内容是一样的'''
content=input('请输入一句话:')
tmp=[]
new=''
for i in content:
tmp.insert(0,i)
for i in tmp:
new+=i
if content==new:
return '这是一个回文联'
else:
return '这不是一个回文联'
print(huiwenlian())
|
import datetime
import os
"""
一 编写with操作类Fileinfo(),定义__enter__和__exit__方法。完成功能:
1.1 在__enter__方法里打开Fileinfo(filename),并且返回filename对应的内容。如果文件不存在等情况,需要捕获异常。
1.2 在__enter__方法里记录文件打开的当前日期和文件名。并且把记录的信息保持为log.txt。内容格式:"2014-4-5 xxx.txt"
"""""
class Fileinfo(object):
def __init__(self,fileName):
self.fileNa... |
def power(x,y):
if y:
return x*power(x,y-1)
else:
return 1
print(power(5,0)) |
# https://www.hackerrank.com/challenges/capitalize/problem
def solve(s):
return " ".join(word.capitalize() for word in s.split(" "))
|
def swap_case(s):
return "".join([char.lower() if char.isupper() else char.upper()
for char in s])
|
# -*- coding: utf-8 -*-
message="This is regarding getting confirmation from you to have your time. Are you available now ?" #edit with your message here
title="Message from administrator" #edit with your title here
import Tkinter as tk
import tkMessageBox as messagebox
root = tk.Tk().withdraw()
value=messagebox.... |
"""You are in a room with a circle of 100 chairs. The chairs are numbered sequentially from 1 to 100.
At some point in time, the person in chair #1 will be asked to leave. The person in chair #2 will be skipped, and the person in chair #3 will be asked to leave. This pattern of skipping one person and asking the next ... |
# stolen from the interwebz
class Node:
def __init__(self,value,next):
self.value = value
self.next = next
def prnt(n):
next = n.next
print n.value
if(next is not None):
prnt(next)
#Iterative
def reverse(n):
previous = None
current = n
while current is not None:
next = current.next
... |
def count(lst):
even=0
odd=0
for i in lst:
if i %2==0:
even+=1
else:
odd+=1
return even,odd
lst=[1,2,3,44,5]
even,odd= count(lst)
print(even,odd)
|
# class variables and instance variables or namespaces
# class method and instance method(accesor andd mutator) and static method
class student:
# class variable
school="myworld"
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
def sum(self):
return (self.m1+self.m2)
... |
def selectionsort(list):
for i in range(0,len(list)):
p=i
for j in range(i,(len(list))):
if list[p]>list[j]:
p=j
t=list[i]
list[i]=list[p]
list[p]=t
list=[8,9,2,4,7]
selectionsort(list)
print(list)
|
x=["name","movies","python"]
print(x[1])
print("i like"+ x[1])
|
from typing import Iterable
from AuxiliaryMethods import *
import random
"""
Lecture 5 Sorting
"""
# Selection Sort
# O(n^2)
def selectionSort(A: Iterable[int], lo: int, hi: int) -> None:
"""
Implementation of selection sort
requires 0 <= lo and lo <= hi and hi <= len(A)
ensures isSorted(A, lo, hi)
... |
start_num = 1
logest_chain = 0
big_num_long_chain = 0
while start_num < 1000000:
# I start from 2
start_num = start_num + 1
# The chain length starts from 1, the starting number is counted in the chain
chain_length = 1
chain_number = start_num
# Repeat the process until the number isn't 1
while chain_number !... |
from tkinter import *
from tkinter import ttk
from tkinter.scrolledtext import *
# from demopanels import msgpanel, seedismisspanel
TXT = """
This window is a scrolled text widget. It displays one or more lines of text
and allows you to edit the text. Here is a summary of the things you
can do to a text ... |
class GridWorld:
# 4 x 4 그리드 월드
x = 0
y = 0
def step(self, a):
if a == 0:
self.move_right()
elif a == 1:
self.move_left()
elif a == 2:
self.move_up()
else:
self.move_down()
# 보상은 언제나 -1
reward = -1
... |
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
print(L[0:3]) #['Michael', 'Sarah', 'Tracy']
print(L[:3]) #['Michael', 'Sarah', 'Tracy']
print(L[1:3]) #['Sarah', 'Tracy']
print(L[1:]) #[ 'Sarah', 'Tracy', 'Bob', 'Jack']
print(L[-1]) #['Jack']
print(L[-2:]) #'Bob', 'Jack'
print(L[-2:-1]) #Bob', 'Ja... |
from urllib import request
from urllib import parse
base_url ='http://www.baidu.com/s?'
wd = input("输入搜索关键字")
qs = {
'wd':wd
}
print(qs) #{'wd': 'aaa'}
qs = parse.urlencode(qs) #转换url编码
print(qs) #wd=aaa
#拼接url
fullurl = base_url + qs
response = request.urlopen(fullurl)
html = response.read().decode('utf-8')... |
#area of circle
pi=3.14
r=2
area=pi*r*r
print(area)
|
#!/bin/python3
# -*- coding: utf-8 -*-
# ship.py
# @author 刘秋
# @email lq@aqiu.info
# @description 飞船的类
# @created 2019-08-16T11:21:33.165Z+08:00
# @last-modified 2019-08-23T10:41:30.305Z+08:00
import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
"""飞船类"""
def __init__(self, ai_settings, scre... |
import os
import Conversao
import SomaBinario
import SubtracaoBinario
import MultiplicacaoBinario
import DivisaoBinario
def menu_principal():
while(True):
print("BEM VINDO A CALCULADORA BINÁRIA\n")
print("===== MENU INTERATIVO =====")
print("O QUE DESEJA FAZER?\n")
... |
'''
Created on 04.07.2014
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, ... |
num = int(input("Enter a number: "))
m = num % 2
if m > 0:
print(" an odd.")
else:
print("an even .")
|
class Tris:
def __init__(self):
self.l = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
def pieno(self, x, y):
return self.l[(x - 1) * 3 + y - 1] != " "
def inserisci_la_giocata(self, x, y, g):
self.l[(x - 1) * 3 + y - 1] = g
def stampa_il_campo(self):
print(self.l[0] + "|" + self.l[1] + "|" ... |
def power(n):
while (n % 2 == 0):
n /= 2;
return n == 1;
n=int(input())
if power(n):
print("yes")
else:
print("no")
|
from binary_search_tree import BinarySearchTree
import time
start_time = time.time()
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n") # List containing 10000 names
f.close()
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n") # List containing 10000 names
f.close()
binary_tree = BinarySearchTre... |
'''
Created on Apr 11, 2018
@author: riccga
'''
from random import randint
sbank = 60
bank = sbank
point = 'off'
bet = 5
odds = 0
def roll_dice():
dice = randint(1,6)
return dice
bank = bank - bet
print bank
print "Bet is $" + str(bet)
dicea = roll_dice()
diceb = roll_dice()
... |
import typing
import numpy as np
from data import SecretaryInstance
def secretary_algorithm(all_candidates, max_colors) -> SecretaryInstance:
"""This method runs the first baseline: the Secretary Algorithm
Args:
all_candidates ([SecretaryInstance]): List of all candidates
max_colors ([string]... |
def parse_fasta(fasta_file):
sequence = ''
with open(fasta_file) as f:
for line in f:
if not line.startswith(">"):
sequence += line.strip()
return sequence
|
"""
This class represents a cell in a maze, or a state.
Each cell stores not only its own cost, but the cost of the path up to it, and the path leading toward it.
"""
class Cell:
def __init__(self, row, col, loc, value, cost, path_cost, path):
self.parent = None
self.row = row
self.col ... |
import math
def is_prime(num):
for i in range(2, math.ceil(math.sqrt(num))):
if not num % i:
return False
return True
def field_in():
field = int(input("input the size of field Z: "))
if not is_prime(field):
print("this is not a field")
return field
def polynomial_i... |
def prime(no):
cnt=1
for i in range(2,no):
if no%i==0:
cnt=0
break
if cnt == 1:
print("Number is prime")
else:
print("Number is not prime")
print("Enter the number")
no=int(input())
prime(no)
|
class FilterTest:
__doc__ = '''
和map()类似,filter()也接收一个函数和一个序列。
和map()不同的是,filter()把传入的函数依次作用于每个元素,
然后根据返回值是True还是False决定保留还是丢弃该元素。
'''
def __init__(self):
self.seq = None
pass
def oddnums_iter(self):
n = 1
while True:
n = n + 2
yield ... |
'''
TO DO:
abstract into class.
add decks.
'''
from sys import argv
from random import choice
import pickle
class ArdenDeck:
def __init__(self, deckType):
self.deck = {}
def setDeck(self, deck):
self.deck = deck
def initCards(self):
self.deck = {}
self.deck['type'] = "standard"
self.deck['cards'] ... |
#builtin modules-random module
import random#importing module
for i in range(3):
print(random.random())#returns value btw 0 and 1
for i in range(3):
print(random.randint(10,20))#returns arbitrary value btw 10 and 20(included)
#if u want to randomly choose something
members=['Cel','galdin','sheena','joy']
leader... |
#pb
prev='stop'
inst=input('<').lower()
while inst!='quit':
if inst=='help':
print('start-to start the car')
print('stop-to stop the car')
print('quit-to exit')
elif inst=='start':
if prev==inst:
print('hey, the car has already started')
else:
prin... |
#nexted loop;print all 2D coordinates possible with 0<=x<=3 and 0<=y<=2
for i in range(4):
for j in range(3):
print(f'({i},{j})') |
class hashtable:
def __init__(self):
self.max=100
self.arr=[None for i in range(self.max)]
def get_hash(self,key):#our hash fn is sum of ascii values of key modulus 100
sum=0
for char in key:
sum+=ord(char)#returns ascii value of character
return sum%self.max... |
#!/usr/bin/env python2.7
import sys
import random
greetings = ("hi", "hello", "how are you,")
responses = ["well hello there", "hey", "wassup?"]
input = raw_input("Please enter a message: ")
def respond_to_greeting(input):
for word in input.split():
if word.lower() in greetings:
return random.choice(res... |
from math import pi
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def division(num1, num2):
return num1 / num2
def remainder(num1, num2):
return num1 % num2
def squared(num, indices... |
# Задача - 1
# Опишите несколько классов TownCar, SportCar, WorkCar, PoliceCar
# У каждого класса должны быть следующие аттрибуты:
# speed, color, name, is_police - Булево значение.
# А так же несколько методов: go, stop, turn(direction) - которые должны сообщать,
# о том что машина поехала, остановилась, повернула(ку... |
def how_many_trees(tree_map, x_slope, y_slope):
x = 0
y = 0
trees = 0
while y <= len(tree_map) - 1:
if tree_map[y][x % len(tree_map[y])] == "#":
trees += 1
y += y_slope
x += x_slope
return trees
def get_input():
with open("input.txt") as f:
return [l... |
def make_seat_map():
return [[0, 0, 0, 0, 0, 0, 0, 0] for y in range(128)]
def populate_seat_map(boarding_passes, seat_map):
for boarding_pass in boarding_passes:
y = [i for i in range(128)]
x = [i for i in range(8)]
for index, instruction in enumerate(boarding_pass):
if in... |
''' Car Price Prediction '''
import pandas as pd
import seaborn as sns
df=pd.read_csv("D:/Studies/Course Material/car_price_prediction_project/car data.csv")
df.head()
df.dtypes
df.columns
col=[col for col in df.columns if df[col].dtypes=='object']
col.pop(0)
# to find the unique categories for... |
import sys
print("Command line arguments have been passed: ")
i = 0
for arg in sys.argv:
if i == 0:
print("This one doesn't count " + str(sys.argv[i]))
else:
print(sys.argv[i])
i += 1
|
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from scipy import signal
from PIL import Image
# -- Read an image --
# Attribution - Bikesgray.jpg By Davidwkennedy (http://en.wikipedia.org/wiki/File:Bikesgray.jpg) [CC BY-SA 3.0 (http://creativecommons.org/licenses/by-sa/3.0)], via W... |
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
def main():
# animals = {
# "kitten": "meow",
# "puppy": "ruff!",
# "lion": "grrr",
# "giraffe": "I am a giraffe!",
# "dragon": "rawr",
# }
animals = dict(
kitten="meow",
puppy="ruff!",
... |
def sup21(nombre):
if nombre >= 21:
return True
return False
test_ = sup21(1)
def pairs(liste):
liste_paires = [liste[i] for i in range(len(liste)) if liste[i] % 2 == 0]
return liste_paires
le = [1, 2, 4]
print(pairs(le))
def ajout4(liste):
nouv = liste.copy()
nouv.append(4)
... |
from abc import ABCMeta, abstractmethod
class ProgressBarBase(metaclass=ABCMeta):
@abstractmethod
def set_title(self, title):
"""
Sets informative text about what the progress bar is indicating the progress of
"""
pass
@abstractmethod
def set_position(self, position... |
import os
BOARD_TOP = ['''
|/ \|/ \| |/ |/ | |/
| \| \|/ \| |/ \|/ \|\|/ |/
| | | | | | | | |
^^^^^^^^^^^^^^^^^^^| |^^^^^^^^^^^^^^^^^^^''']
BOARD_LEVELS = ['''~~~~~~~~~~~~~~~~~~~|____... |
#Strings e bytes não são diretamente intercambiáveis
#Strings contém unicode, bytes são valores de 8 bits
def main():
#Definindo valores iniciais
b = bytes([0x41, 0x42, 0x43, 0x44])
print(b)
s = "Isso é uma string"
print(s)
#Tentando juntar os dois.
#print(s + b)
#Bytes e strings pr... |
# Usando métodos mágicos para comparar objetos entre si
class Pessoa:
def __init__(self, nome, sobrenome, nivel, anos_trabalhados):
self.nome = nome
self.sobrenome = sobrenome
self.nivel = nivel
self.senioridade = anos_trabalhados
# TODO: Implemente as comparações usando o nív... |
#Demonstração de algumas funções built-in úteis.
def main():
# Usando any() e all() para testar valores boleanos
lista = [1, 2, 3, 4, 5, 6]
# Retorna true caso qualquer valor da lista seja verdade
print(any(lista))
# Retorna True se todos os valores da lista forem verdade
print(all(lista))
... |
#Define a global empty dictionary. Iterate from 1 till 10 and fill the dictionary
# with the key as the number and value as the square of that number.
#reference from google
d={}
def add_values(x,y):
d[x]=y
a=1
while(a<10): # prints uptil 10 items
x=eval(input("Enter key {}:".format(a)))
y=eval(input("ENt... |
#Using the above dictionary, print the following output.
#Aex
#class : V
#rolld_id : 2
#Puja
#class : V
#roll_id : 3
students = {
'Aex':{'class':'V', 'rolld_id':2},
'Puja':{'class':'V', 'roll_id':3 }
}
for a in students:
print(a)
for b in students[a]:
print (b,':',stu... |
#Sort this dictionary ascending and descending.
import operator
d = {7: 2, 9: 4, 4: 3, 2: 1, 0: 0}
print('Original dictionary : ',d)
sorted_d = dict (sorted(d.items(), key=operator.itemgetter(1))) #sort in ascending
print('Dictionary in ascending order by value : ',sorted_d)
sorted_d = dict( sorted(d.items(), key=ope... |
#Write a Python program to count the number of strings in a list
# where the string length is 2 or more
# and the first and last character are the same from a given list of strings.
list1 = ["himani","maheta","aba"]
def match_words(list1):
ctr = 0
for word in list1:
if len(word) > 1 and word[0] == word[-1]:... |
while True:
var = input("suuuuup?").lower()
print("you chose: " + var)
import random
choice = random.choice(["rock","paper", "scissors"])
if var == "rock" or var == "paper" or var == "scissors":
print("we pick: " + choice)
if var == choice:
print("draw")
elif var =="rock" and choice... |
#!/usr/bin/env python
# this is a python 2.x file due to dpkt dependency
#
# pcap_analyser.py
#
# Copyright 2014 Tim auf der Landwehr <dev@taufderl.de>
#
# This script provides a pcap data analyser.
# It is able to count all packets in a pcap file,
# find IP packets and distinguish TCP and UDP packets.
# In addi... |
while True:
number = int(raw_input("Enter a number:"))
check = int(raw_input("Give me another number to divide by:"))
if number % 2 == 0:
print ("{0} is an Even Number").format(number)
elif number % 4 == 0:
print ("{0} is a multiple of 4").format(number)
else:
print... |
import time
import random
class Engine:
def __init__(self, wordlist, kelime_sayaci):
self.wordlist = wordlist
self.kelime_sayaci = kelime_sayaci
self.zaman = time.perf_counter()
self.counter = 0
self.output = ""
self.wrong_counter = 0
def get_sentences(sel... |
def parse(line):
return line.strip()
with open("input.txt") as f:
lines = f.readlines()
input = [parse(line) for line in lines]
def analyze(numbers):
zeroes = [0 for _ in numbers[0]]
ones = [0 for _ in numbers[0]]
for l in numbers:
for i, c in enumerate(l):
if c == '0':
... |
def print_expr(expr, pos):
print(" " * pos + "v")
print(expr)
moves = {"W": (-1, 0), "E": (1, 0), "N": (0, -1), "S": (0, 1)}
def parse(expr, pos, distances, start_x, start_y):
x, y, length = start_x, start_y, distances[(start_x, start_y)]
while expr[pos] != "$" and expr[pos] != ")":
print_exp... |
# test
# puzzle_input = "389125467"
# real
import typing
puzzle_input = "135468729"
class Node:
def __init__(self, val, prev=None, next=None):
if prev is None: prev = self
if next is None: next = self
self.val = val
self.prev = prev
self.next = next
class Circle:
d... |
FILE = "input.txt"
with open(FILE) as f:
seats = [list(line.strip()) for line in f]
FLOOR = '.'
EMPTY = 'L'
OCCUPIED = '#'
def nearby(row, col, seats):
top = max(row-1, 0)
bottom = min(row+2, len(seats))
left = max(col-1, 0)
right = min(col+2, len(seats[0]))
return sum(1 for row in seats[top:... |
from breadth_first import breadth_first
with open("input.txt") as f:
map = [line.strip() for line in f]
allkeys = set()
start_x, start_y = 0, 0
for y, row in enumerate(map):
for x, cell in enumerate(row):
if cell == '@':
start_x, start_y = x, y
elif cell in 'qwertyuiopasdfghjklzxc... |
SNAFU_DIGITS = {
'=': -2,
'-': -1,
'0': 0,
'1': 1,
'2': 2,
}
DIGITS_SNAFU = {v: k for (k, v) in SNAFU_DIGITS.items()}
def unSNAFU(snafu):
answer = 0
for c in snafu:
answer *= 5
answer += SNAFU_DIGITS[c]
return answer
def parse(line):
return unSNAFU(line)
with ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.