text stringlengths 37 1.41M |
|---|
nums = [1,2,3,4,5]
#regular
for num in nums:
print(num)
print('-----')
#break
for num in nums:
if num==3:
print(num,"is found, Chimp has it!!")
break
print(num)
print('-----')
#continue
for num in nums:
if num==3:
print(num,"is found, Chimp has it!!")
continue
print(num)
print('-----')
... |
#Sets are unordered and no deplicates list
courses = {'Maths', 'Physics','Chemistry', 'Computer Sci', 'Maths'}
print(courses)
print('Maths' in courses)
cs_courses = {'Java','Angular', 'Maths', 'Computer Sci'}
print(cs_courses .intersection(courses))
print(cs_courses.difference(courses))
print(cs_co... |
class Node:
def __init__(self, key, value, left=None, right=None, size=1):
assert ((left is None or isinstance(left, Node)) and
(right is None or isinstance(right,Node)))
self.key = key
self.value = value
self.left = left
self.right = right
self.size ... |
s1 = 'abcdefg'
s2 = 'cdefghi'
def fn(s1,s2):
if len(s1) < len(s2):
s1,s2 = s2,s1
maxstr = s1
substr_maxlen = max(len(s1),len(s2))
for sublen in range(substr_maxlen,-1,-1):
for i in range(substr_maxlen-sublen+1):
if maxstr[i:i+sublen] in s2:
return maxstr[i:i+... |
#! /usr/bin/python
# D:{SADASANT;}
import euler
def euler0019(d,m,y): # d must be 31, m must be 12, y must be 2000 in order to solve the problem
""" How many Sundays fell on the first of the month during the twentieth century? """
D,M,Y = 1,1,1901
m30d = [4,6,9,11]
m31d = [1,3,5,7,8,10,12]
week = {1:'monday',... |
#! /usr/bin/python
# D:{SADASANT;}
import euler
def euler0009(n): # n must be 1000 in order to solve the problem
""" Find the only Pythagorean triplet, {a, b, c}, for which a + b + c = 1000. """
l = []
for x in range(1,n/2):
l.append(x)
for xxx in l:
for xx in l:
for x in l:
if x<xx<xxx an... |
#! /usr/bin/python
# D:{SADASANT;}
import euler
def euler0016(n,e): # n must be 2 and e must be 1000 in order to solve the problem
""" What is the sum of the digits of the number 2**1000? """
N = n**e
print N
R = 0
for x in str(N):
R+=int(x)
return R
print euler0016(2,1000)
|
def mdc(a, b):
return a if b == 0 else mdc(b, a % b)
def mmc(a, b):
return abs(a * b) / mdc(a, b)
while True:
try:
lastAlign = int(input())
line = input().split(' ')
l1 = int(line[0])
l2 = int(line[1])
l3 = int(line[2])
days = int(mmc(mmc(l1, l2), l3) - la... |
import numpy as np
import maze as m
# the neighbors checked when scanning neighbors
neighbors = [
(-1, 0), # one space above
(1, 0),
(0, -1),
(0, 1),
]
# the search starts at [start[0]][start[1]] and searches for [end[0][end[1]]
# only works for rectangular mazes
# assumes the params are valid
def dfs... |
# Dictionary Stuff
print("Hello World");
test = {'color':'green','points':5};
print(test['color']);
print(test['points']);
test['xPos'] = 0;
test['yPos'] = 25;
test['dummydata']='deleteme';
print(test);
del test['dummydata'];
print(test);
#===========================================
favLang = {'Chris':'C#','Hazel':... |
def sort_stupid(sort_list):
iteration = 0
for i in range(len(sort_list) - 1):
for j in range(len(sort_list) - i - 1):
iteration += 1
if sort_list[j] > sort_list[j + 1]:
sort_list[j], sort_list[j + 1] = sort_list[j + 1], sort_list[j]
return [sort_list, i... |
# Informatika érettségi 2012 május programozás----------
# 1.feladat --------------------------------------------
utak = []
with open('tavok.txt','r') as fbe:
for sor in fbe:
s = sor.split()
utak.append([int(s[0]),int(s[1]),int(s[2])])
utak = sorted(utak)
# 2. feladat -------------------... |
# Parkettázás
import math
# --- negyzet() függvény ----
def negyzet():
a = float(input('A négyzet oldala: '))
t = a * a
print('Terület:',math.ceil(t))
print('Költség:',ar * math.ceil(t))
# --- teglalap() függvény ----
def teglalap():
pass
# --- Főprogram ---
ar = 1000
print('Parke... |
# Hőmérséklet statisztika
feb = [2,1,5,-3,3,2,8,-5,1,2,2,-5,0,5,
-3,5,-3,3,-21,1,-9,-2,1,1,-9,-12,0,-5]
while True:
print('1-Átlag 2-Min 3-Max 4-Fagy 5-Javít '+
'6-Diagram 0-Kilép')
v = input('Választás: ')
if v == '1':
print('Átlag:',sum(feb)/len(feb))
elif v == '2... |
# Mit vegyek fel?
# Be: t
t = int(input('Hány fok van? '))
# Ha t < 10
# Ki: kabátot vegyél fel!
# Egyébként ha t < 20
# Ki: pulóvert vegyél fel!
# Egyébként
# Ki: pólót vegyél fel!
if t < 10:
print('Kabátot vegyél fel!')
elif t < 20:
print('Pulóvert vegyél fel!')
else:
print('Pól... |
# -*- coding: utf-8 -*-
def fib(n):
a, b = 1, 1
while n:
a, b = b, a + b
yield a
n -= 1
if __name__ == '__main__':
# [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
print([i for i in fib(10)])
|
import thorpy, pygame
application = thorpy.Application((500,500), "Launching alerts")
# ****************** First launcher : button 1 ******************
#This launcher launches a simple button
my_element = thorpy.make_button("I am a useless button\nClick outside to quit.")
button1 = thorpy.make_button("Laun... |
input_file = 'data.txt'
# input_file = 'testdata.txt'
with open(input_file, 'r') as f:
data = f.readlines()
ROCK = 1
PAPER = 2
SCISSORS = 3
mapA = {'A': ROCK,
'B': PAPER,
'C': SCISSORS}
mapX = {'X': ROCK,
'Y': PAPER,
'Z': SCISSORS}
point_sum = 0
def compareAX(A, X):
"""
>... |
input_file = 'data.txt'
# input_file = 'testdata.txt'
with open(input_file, 'r') as f:
data = f.readlines()
priorities = 0
def get_priority(a):
"""
>>> get_priority('a')
1
>>> get_priority('p')
16
>>> get_priority('z')
26
>>> get_priority('A')
27
>>> get_priority('P')
... |
"""
This file will contain all the functions which will allow us to interact with PostgreSQL (our relational DB).
Note: we have created the user and the database using pgAdmin.
"""
import psycopg2
from timeSeriesDB import resources as res
from influxdb import InfluxDBClient
def connect_postgres():
"""
This f... |
"""
Basic mathematical functions operate element-wise on arrays. They are available both as operator overloads and as functions in the NumPy module.
import numpy
a = numpy.array([1,2,3,4], float)
b = numpy.array([5,6,7,8], float)
print a + b #[ 6. 8. 10. 12.]
print numpy.add(a, b) ... |
## Chapter 05 | Exercise 01
# Write a program which repeatedly reads numbers until the user enters “done”.
# Once “done” is entered, print out the total, count, and average of the numbers.
# If the user enters anything other than a number, detect their mistake using try and except
# and print an error message and skip ... |
## Chapter 04 | Exercise 01
## Section 4.5: Random Numbers
# Run the program (pg. 46) on your system and see what numbers you get.
# Run the program more than once and see what numbers you get.
import random
for i in range(10):
x = random.random()
print(x)
|
# ASSIGNMENT INSTRUCTIONS | Ch 08, Problem 04
#
# Open the file romeo.txt and read it line by line. For each line, split the
# line into a list of words using the split() method. The program should
# build a list of words. For each word on each line check to see if the word is
# already in the list and if not append it... |
## Chapter 12 | Exercise 03 (Week 4)
## Following Links in Python
"""
In this assignment you will write a Python program that expands on http://www.py4e.com/code3/urllinks.py. The program will use urllib to read the HTML
from the data files below, extract the href= vaues from the anchor tags, scan for a tag that is i... |
## Chapter 12 | Exercise 02 (Week 4)
## Scraping Numbers from HTML using BeautifulSoup
"""
In this assignment you will write a Python program similar to http://www.py4e.com/code3/urllink2.py. The program will use urllib to read the HTML from the data files below, and parse the data, extracting numbers and compute the ... |
class Node:
def __init__(self,val):
self.__val=val
self.__left=None
self.__right=None
def getVal(self):
return self.__val
def getLeft(self):
return self.__left
def getRight(self):
return self.__right
def setLeft(self,node):
self.__left=node... |
# # create a class instance of an employee
# class Employee:
# raise_amount = 1.05
# num_of_employees = 0
# def __init__(self, first_name, last_name, email, salary):
# self.first_name = first_name
# self.last_name = last_name
# self.email = email
# self.salary = salary
# ... |
# test data = [10,1,20,3,4,6,0]
def insertionsort(ulist):
for i in range(1,len(ulist)):
current=ulist[i]
while i>0 and ulist[i-1]>current:
ulist[i]=ulist[i-1]
ulist[i-1]=current
i=i-1
print(ulist)` 1 |
import time
start = time.time()
for i in range(1,100000001):
'Number {} squared is {} and cubed is {}'.format(i, i**2, i**3)
#print('Number {} squared is {} and cubed is {}'.format(i, i**2, i**3))
end = time.time()
total_time = end - start
print(total_time,'seconds')
print(total_time/60,'minutes')
|
"""Simple helper to paginate query
"""
import math
from mongoengine.queryset import QuerySet
DEFAULT_PAGE_SIZE = 10
DEFAULT_PAGE_NUMBER = 1
__all__ = ("Pagination",)
class Pagination(object):
"""
This is class for paginate
"""
def __init__(self, iterable, page=None, per_page=None):
self.it... |
from typing import Generator
def read_lines(file_path: str) -> Generator[str, None, None]:
""" Generator that yields clean lines from 'input.txt'; relative to the current working directory. """
with open(file_path, 'r') as fp:
for line in fp.readlines():
yield line.strip()
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Speciallan
class Solution(object):
def scoreOfParentheses(self, S):
"""
:type S: str
:rtype: int
"""
if len(S) == 0:
return 0
S = S.replace('()', '1')
arr = []
total = 0
for ... |
#!/usr/bin/env python3
import psycopg2
from psycopg2 import Error
DBNAME = "news"
# 1. What are the most popular three articles of all time?
query1 = """Select articles.title AS article, count(*) AS views
FROM log, articles
WHERE log.path = (concat('/article/',articles.slug))
GROU... |
from __future__ import print_function
from collections import defaultdict
class Node(object):
def __init__(self, value):
self.value = value
self.isvisited = False
def __str__(self):
return (self.value)
class Graph(object):
def __init__(self):
self.vertices = defaultdict(lis... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 16 19:48:59 2020
@author: ANGELO
"""
def hiEverybody(myList):
for name in myList:
print("Hi,", name)
hiEverybody(["Adam","John","Lucy"])
def createList(n):
myList = []
for i in range (n):
myList.append(i)
return ... |
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 思路:
# 1. 先判断是否存在环,若存在,返回一个环内节点
def getNodeOfLoop(self, pHead):
if pHead is None:
return None
# 两个指针,一快,一慢
p_slow = pHead
p_fas... |
# -*- coding:utf-8 -*-
class Solution:
# s字符串
def isInt(self, s):
# 整数判断:
# 1. 为空
# 2. +,- 或者 1-9 开头,后面取值全是0-9
# (2.1) + 或者 - 开头,后面需要有值
# (2.2) 1-9开头,后面可以无值
if len(s)==0:
return True
if s[0]=='+' or s[0]=='-':
if len(s)... |
# -*- coding:utf-8 -*-
class Solution:
def LeftRotateString(self, s, n):
# 思路: 将循环右移 取余
# 1. 长度为 len 的字符串,左移 len 还是它本身
# 2. 循环左移 n 相当于将 字符串 0-n的字符串 补 n-len的字符串后面
str_len = len(s) # 字符串长度
if str_len < 1: # 特殊情况,字符串为空
return ""
final_n = n%str_len
... |
# Several common sorting algorithms: ascending
# 1. Bubble Sort
def bubble_sort(nums):
nums_len = len(nums)
for i in range(0, nums_len):
sign = True
for j in range(0, nums_len-i-1):
if nums[j+1] < nums[j]:
sign = False
nums[j], nums[j+1] = nums[j+1], n... |
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# 使用栈的方式
'''
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
array_list = []
ll = listNode
while ll is not None:
arr... |
class Solution:
# 返回ListNode
# 思路:不借助额外存储空间
def ReverseList(self, pHead):
# write code here
if pHead is None:
return pHead
p0 = None
p1 = pHead
while p1 is not None:
tmp = p1.next # 获得下一个节点
# 每次改变一个链接方向
p1.next = p0
... |
from random import shuffle
class Card:
number_face = {11: "jack", 12: "queen", 13: "king"}
def __init__(self, number, suit):
self.number = number
self.suit = suit
self.has_face = False
# Try catch block?
if self.suit == "clubs" or self.suit == "spades":
self.color = "black"
elif self.suit == "hearts"... |
number = 1
count = 0
largest = 0
while (number > 0):
number = float(input('Please enter a number'))
if (number > largest):
largest = number
print('Largest Number = ',largest)
|
def add(**arg):
sum = 0
for value in arg.values():
sum = sum + value
return sum
def multiple(a,b):
mul = a * b
return mul
print(add(a=5,b=7,c=8,d=10))
|
'''Diff_string will take two string as input and retrun the location where first diff occured'''
string1 = input('Please enter a name ')
string2 = input ('Please enter second name ')
def match_func(string1, string2):
i = 0
mismatch = 'N'
while i < len(string1) and i < len(string2) :
if string1[i]... |
# basic types - numbers
# int() converts string to an interger
print(int('5') + int('3')) |
import os
import csv
# Path to collect data from the Resources folder
PybankCSV = os.path.join('Resources', 'budget_data.csv')
# Read in the CSV file
with open(PybankCSV, 'r') as csvfile:
# Split the data on commas
csvreader = csv.reader(csvfile, delimiter=',')
header = next(csvreader)
total =... |
"""
scraper.py defines the YahooScraper class to scrape yahoo for finance data.
"""
import pickle
import re
import requests
class YahooScraper():
"""Scrapes Yahoo Finance for data"""
def __init__(self, features, feature_source_map, source_path):
self.features = features
self.feature_source_ma... |
#!/cconjecture/ex.py
import algorithm as a
def getInput():
num = input("what number do you want to test?")
while True:
try:
num = int(num)
if num > 0:
return num
else:
print("please enter an integer greater than 0")
con... |
import csv
import json
INPUT_CSV = 'data.csv'
YEAR = '2016'
def csv_to_json(input_file):
csv_file = open(input_file, 'r')
json_file = open('data.json', 'w')
reader = csv.DictReader(csv_file)
list = []
# Makes list of dictionaries of which country has how much renewable energy for the year
f... |
import random
difficulty = input("What difficulty would you like? easy, medium or hard\n").lower()
guess_limit = 6
chances_left = 6
guess_taken = 0
while difficulty == "easy":
try:
random_number = random.randint(1, 10)
guess = int(input("Enter a number between 1 - 10: "))
guess_taken += 1
... |
#!/bin/python
import sys
import copy
from cell import Cell
from board import Board
from minimax import getNextMove
from minimax import interfaceBoard
class DoubleCard():
def __init__(self):
self.board = Board()
self.turn = 0
self.prev_board = copy.deepcopy(self.board)
self.trace = ... |
#!/Users/amod/venv/bin/python
#Date: 27march 2020
# this program takes inputs fom the user and sorts them into numbers and strings
a = input("type anything")
b = input("type anything")
c = input("type anything")
d = input("type anything")
e = input("type anything")
f = input("type anything")
g = input("type anything")
... |
#!/Users/amod/venv/bin/python
# Author Name : Amod gawade
# Date : 20 march 2020
print("Program start")
# Taking input from user
k = input("Enter a value for speed(in KmPH) : ")
# converting to miles per hour
m = int(k)/1.609
print("The speed in miles per hour is %.2f" % m)
print("Program ends")
|
#!/Users/amod/venv/bin/python
# Author name : Amod Gawade
# Date : 29 March 2020
print("Program starts")
# Taking input from user
num1 = input("Enter a Value : ")
# Calculating the sqrt of num1
square_root = int(num1)**0.5
print("The square root of %s is %f" % (num1, square_root))
print("Program ends")
|
#!/Users/amod/venv/bin/python
# Author : Amod Gawade
# Date:29 march 2020
print("Program Starts")
# Requesting the Inputs to add two numbers
a = input("Enter a value of A: ")
b = input("Enter a value of B: ")
# Performing the Arithmetic Addition
c = (int(a)+int(b))
# Printing the Result statements
print("The Additi... |
list=[1,2,3,4,5,6,7,8,9]
def listdouble():
for i in range(len(list)):
if list[i]%2==1:
print('tek ededleri goster: ', list[i] )
else:
print('cut ededleri goster: ', list[i])
listdouble() |
x=3
y=50
def bolunme3():
for i in range(x,y):
if i%3==0:
print("three: ", [i])
bolunme3()
def bolunme5():
for i in range(x,y):
if i%5==0:
print("Five: ", [i])
bolunme5()
def bolunme3ve5():
for i in range(x,y):
if i%... |
shopping_list = ["milk", "ham", "spam", "pasta"]
item_to_find = "spam"
found_at = None
# for index in range(len(shopping_list)):
# if shopping_list[index] == item_to_find:
# found_at = index
# break
if item_to_find in shopping_list:
found_at = shopping_list.index(item_to_find)
if found_at is... |
"""Implement a base class for games created using PyGame."""
import pygame
class Game:
"""Base class for a PyGAme game."""
def __init__(self):
"""Initializes the game object."""
self.running = False
def run(self):
"""Runs the game."""
self.running = True
... |
################ PERFORMING PREPROCESSING OF INPUT TEXT ###################
def preprocess_text(df, column):
import re
for i in range(len(df)):
###### REMOVING SPECIAL CHARACTERS
df.loc[i, column] = re.sub(r'\W', ' ', str(df.loc[i, column]))
###### REMOVING ALL SINGLE CHARACTERS
... |
from unittest import TestCase
from recon import Reconciliation
from decimal import Decimal
class ReconciliationTest(TestCase):
"""Customer Account Reconciliation Tests"""
def setUp(self):
self.recon = Reconciliation()
def test_empty(self):
"""test that new/empty Reconcillation object has ... |
#Problem link: https://www.spoj.com/problems/TEST/
#Time complexity: O(1)
#Space complexity: O(1)
ip = True
while True:
n = int(input())
if n==42:
break
print(n)
|
#Ask user for name
name =input("What is your Name? : ")
#Ask user for age
age =input("What is your age ? : ")
#ask user for city
city = input("What city do you live in ? : ")
#Ask user what they enjoy
love=input("What do you love doing? : ")
#Create output text
string = "Your name is {} and you ar... |
known_users=["Alice","Bob","Clair","Dan","Emma","Fred","George","Harry"]
while True:
print("Hey,Hi! My name is Rohit,")
name=input("What is your name").strip().capitalize()
if name in known_users:
print("Ooh, Hello {}".format(name))
remove=input("Would you like to delete your name from ... |
"""
itertools提供了非常有用的用于操作迭代对象的函数
"""
# "无限"迭代器
"""
count(n) :无限数自然数,间隔为n
cycle(str) :无限重复str
repeat(t, n) :重复t n次
"""
import itertools
natuals = itertools.count(1)
# for n in natuals:
# print(n)
# 使用takewhile()函数截取有限序列
ns = itertools.takewhile(lambda x: x <= 10, natuals)
print(list(ns))
"""Chain()将... |
"""
用sayncio提供的@asyncio.coroutine 可以把一个generator标记为coroutine类型,
然后在coroutine内部用yield from调用另一个coroutine实现异步操作
为了简化并更好地标记异步IO,从Python3.5开始引入新的语法saync和await,可以让coroutine的代码更简洁易读
具体规则:
1. asyncio.coroutine 替换为 async
2. yield from 替换为 await
"""
# 与sayncio对比
import asyncio
async def hello():
print('He... |
"""
Iterator=map(func, Iterable)
"""
from functools import reduce
def f(x):
return x*x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(r))
# int->str
print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
"""
reduce(f,[x1, x2, x3, x4]) = f(f(f(x1,x2),x3),x4)
"""
def add(x, y):
return x+y
print(redu... |
"""
可迭代对象(Iterable):可以直接作用于for循环的数据类型
包括:
- 集合数据类型,如list tuple dict set str
- generator,() and generator function(yield)
"""
from collections import Iterable
from collections import Iterator
"""判断一个对象是否是Iterable对象"""
print(isinstance((x for x in range(10)), Iterable))
print(isinstance([], Iterable))
... |
"""
TCP是建立可靠连接,并且通信双方都可以以流的形式发送数据
相比TCP,UDP则是面向无连接的协议
使用UDP协议时,不需要建立连接,只需要知道对方的IP地址和端口号,就可以直接发数据包。但是,能不能到达就不知道了。
虽然用UDP传输数据不可靠,但它的优点是和TCP比,速度快,对于不要求可靠到达的数据,就可以使用UDP协议。
"""
import socket
# 使用UDP协议
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定端口
s.bind(('127.0.0.1', 9999))
print('Bind UDP ... |
import sys
class Contador():
def __init__(self,x=0,y=0):
self.__x=x
self.__y=y
def get_x(self):
return self.__x
def get_y():
return self.__y
def set_incremento(self, incremento_x,incremento_y):
self.incremento_x=get_x()+=1
self.incremento_y=get_y()+=1
... |
" Module containing a generator of Fibonacci sequence list."
import numpy as np
def fibo(f_seq):
"""Returns list of FIbonacci sequence elements.
Parameters:
list *f_seq* -- list of Fibonacci sequence elements already computed.
Return:
list of FIbonacci sequence elements """
return np.append(f_seq,f_seq[-1]+f... |
#列
'''try:
print(a)
except: #通吃,不管你遇到什么问题都会处理
print('你好皮!')
else:
print('damon 你可以啊--这么皮!!')'''
#列2
'''try:
print(a)
finally:
print('damon 你可以啊--这么皮!!') '''''
#列3
'''try:
print(a)
except:
print('皮一下')
finally:
pass
list_1=[1,2,3,4]
for i in range(5):
print(list_1[i]) ''... |
def my_function():
my_list = [0, 1, 2, 3, 4, 5]
list_length = len(my_list)
if list_length > 0:
print('list length is greater')
else:
print('list length is lesser')
# try block check whether the statement is executable
try:
list_length1 = len(my_list1)
... |
import math
print(" ********************* WELCOME TO PYTHON CALCULATOR ************************************")
print(" ")
print("PlEASE ENTER YOUR SELECTION")
print("** ADDITION --> 1 ** \n** SUBTRACTION --> 2 ** \n** MULTIPLICATION --> 3 ** \n** DIVISION --> 4 ** \n** POWER --> 5 ** \n** ROOT --> 6 ** ")
print(" ")
Sel... |
#Crear menu con 3 opciones
import os
def Numeros():
pos=0
neg=0
cero=0
cantidad=int(input("Ingrese cantidad de números a ingresar: "))
for i in range(cantidad):
n=int(input(str(i+1)+".-Ingresa un número: "))
if (n>0):
pos+=1
elif (n<0):
neg+=1
... |
def get_indices_of_item_weights(weights, length, limit):
"""
YOUR CODE HERE
"""
# initiaize a cache
cache = {}
# will be increment to make representing indexes
index = 0
# store weights as keys and indexes as values in cache
for weight in weights:
cache[weight] = index
... |
###START###
##I'm very sorry this code doesn't work, but I gave it my best shot!##
def main():
year_won = {}
number_of_wins = {}
year = int(input("What year do you wanna check? "))
infile = open("worldserieswinners.txt", "r")
team_num_wins(infile, number_of_wins)
assign_years(infile, year_won... |
def ArmN(x):
sum=0
t=x
while(t>0):
d=t%10
sum+=d**3
t=t//10
if sum==x:
return 'Armstrong number'
else:
return 'Not A N'
x=int(input())
print(ArmN(x))
|
class hash_map(object):
aMap = []
def __init__(self, table_size):
self.table_size = table_size
for i in range(0, self.table_size):
self.aMap.append([])
def put(self, key,value):
if key is None or value is None :
raise ValueError('Please pass a valid key/value')
hash_location = hash(key) % le... |
vs2=list(input())
if len(vs2)%2==0:
vs2[int(len(vs2)/2)] ='*'
vs2[int(len(vs2)/2)-1]='*'
else:
vs2[int(len(vs2)/2)] ='*'
for i in range(0,len(vs2)):
print(vs2[i],end='')
|
h3,k3=map(int,input().split())
ik=h3+k3
if(ik%2==0):
print("even")
else:
print("odd")
|
g1=int(input())
if(g1>1 and g1<10):
print("yes")
else:
print("no")
|
varshaa=int(input())
shav=0
while varshaa>0:
varshaa=varshaa//10
shav=shav+1
print(shav)
|
ab1=int(input())
ba11=0
l=[]
for ab1 in range(1,ab1+1):
l.append(ab1)
for ab1 in range(len(l)):
for ab1 in range(ab1+1,len(l)):
ba11+=1
print(ba11)
|
"""Author: Cole Howard
Email: uglyboxer@gmail.com
neuron.py is a basic linear neuron, that can be used in a perceptron
Information on that can be found at:
https://en.wikipedia.org/wiki/Perceptron
It was written as a class specifically for network ()
Usage:
From any python script:
from neuron import Neuron
... |
import time
import control
import sensor
## DEFAULT SETTINGS ###
TEMPERATURE = 25
HUMIDITY = 0.8
HOURS_LIGHT = 12
MINUTES_BEFORE_CHECK = 1
while True:
temperature = sensor.get_temperature()
humidity = sensor.get_humidity()
print("current temperature % (C)", str(temperature))
print("current humidity %"... |
#!/usr/bin/env python
import random
with open('groupchoiser/eleves.txt') as x:
names_list = x.read().split()
# is the name marked
def is_name_marked(student_name):
return student_name[-1:] == "+"
def is_group_marked(group):
for name in group:
if is_name_marked(name):
return True
... |
n=input()
if len(n)>7 and len(n)%2!=0:
print(n[(len(n)//2)-1:(len(n)//2)+2])
else:
print("enter a valid odd numbered string") |
word=input()
count=1
length=""
if len(word)>1:
for i in range(1,len(word)):
if word[i-1]==word[i]:
count+=1
else :
length += word[i-1]+" repeats "+str(count)+", "
count=1
length += ("and "+word[i]+" repeats "+str(count))
else:
i=0
length += ("an... |
import letterboxd
from rotten_tomatoes_client import RottenTomatoesClient
import os
import pandas as pd
# create and save database to store multiple user's data
database_name = 'letterboxd'
os.system('mysql -u root -pcodio -e "CREATE DATABASE IF NOT EXISTS '
+ database_name + '; "')
os.system('mysql -u root ... |
from support import get_input_file
def main():
lines = get_input_file.ReadLines(True)
##### PART 1 #####
print("\nDay04 Part 1:\n")
res = validate_numbers(lines, 25, False)
print("The first number to fail the encryption scheme is " + str(res))
##### PART 2 #####
print("\nDay04 Part 2:\n... |
def binarySearch(list,f):
start = 0
end = len(list)-1
while(start<=end):
mid = (start + (end-start) // 2)
if list[mid] is f:
return f
elif list[mid]> f:
end = mid-1
elif list[mid]< f:
start = mid+1
list = [1,2,3,4,5,6 ,7,8,9]
f=int(inp... |
def subsetsUtil(list,subsets,index):
print(subsets)
for i in range(index,len(list)):
subsets.append(list[i])
subsetsUtil(list,subsets,i+1)
subsets.pop(-1)
# print("check")
#print(subsets)
# print("Done")
# else:
# print(subsets)
return
def sub... |
def fact(n):
if n <=1:
return 1
else:
return n*fact(n-1)
if __name__ == '__main__':
n = int(input())
r = fact(n)
print(r) |
a = [2,3,4,5,6,7]
val = 34
pos = 0
temp = 0
for i in range(pos,len(a)):
if i>= pos:
temp = int(a[i])
a[i]=val
val=temp
a.append(temp)
print(a) |
#Programme to take two input numbers from user and print addend of the inputs
print("Watch me amaze and stupify by adding two numbers.")
num1=int(input('Hey... enter your first number...'))
num2=int(input('...alright now your second...'))
num3=str(num1-num2)
print("By my deductive reasoning, your number is - " +num3+"?... |
###Initialising dict and list and choice
#some_dict = {"StudentName":"Keith", "Subjects": ["Web App Development", "Programming and Scripting", "Computer Architecture"]}
list_of_dicts = []
choice = ''
#function to prompt user for what they would like to do
def prompt():
#First I'm just using simple print, then stor... |
#!python
def merge(items1, items2):
"""Merge given lists of items, each assumed to already be in sorted order,
and return a new list containing all items in sorted order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?"""
# TODO: Repeat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.