text stringlengths 37 1.41M |
|---|
"""
See https://turing.cs.hbg.psu.edu/txn131/graphcoloring.html
Examples of Execution:
python3 GraphColoring.py -data=GraphColoring_1-fullins-3.json
python3 GraphColoring.py -data=GraphColoring_1-fullins-3.json -variant=sum
"""
from pycsp3 import *
n, edges, colorings, multiColorings = data # n is the number of... |
"""
My son came to me the other day and said, "Dad, I need help with a math problem."
The problem went like this:
- We're going out to dinner taking 1-6 grandparents, 1-10 parents and/or 1-40 children
- Grandparents cost $3 for dinner, parents $2 and children $0.50
- There must be 20 total people at dinner and it must ... |
"""
Consider two groups of men and women who must marry.
Consider that each person has indicated a ranking for her/his possible spouses.
The problem is to find a matching between the two groups such that the marriages are stable.
A marriage between a man m and a woman w is stable iff:
- whenever m prefers an other woma... |
"""
Problem 110 on CSPLib
Examples of Execution:
python3 PeacableArmies.py -data=10 -variant=m1
python3 PeacableArmies.py -data=10 -variant=m2
"""
from pycsp3 import *
n = data or 6
if variant("m1"):
def less_equal(i1, j1, i2, j2):
if (i1, j1) == (i2, j2):
return b[i1][j1] + w[i1][j1] <... |
"""
See QAPLib and https://en.wikipedia.org/wiki/Quadratic_assignment_problem
Example of Execution:
python3 QuadraticAssignment.py -data=QuadraticAssignment_qap.json
python3 QuadraticAssignment.py -data=QuadraticAssignment_example.txt -dataparser=QuadraticAssignment_Parser.py
"""
from pycsp3 import *
weights, di... |
"""
Dad wants one-cent, two-cent, three-cent, five-cent, and ten-cent stamps.
He said to get four each of two sorts and three each of the others, but I've
forgotten which. He gave me exactly enough to buy them; just these dimes."
How many stamps of each type does Dad want? A dime is worth ten cents.
-- J.A.H. Hunter
E... |
"""
Given a edge-weighted directed graph with possibly many cycles, the task is to find an acyclic sub-graph of maximal weight.
Examples of Execution:
python3 GraphMaxAcyclic.py -data=GraphMaxAcyclic_example.json
python3 GraphMaxAcyclic.py -data=GraphMaxAcyclic_example.json -variant=cnt
python3 GraphMaxAcyclic.p... |
'''
Task:
1. Open a page http://SunInJuly.github.io/execute_script.html.
2. Read the value for the variable x.
3. Calculate the mathematical function of x.
4. Scroll down the page.
5. Enter the answer in the text field.
6. Select the checkbox "I'm the robot".
7. Switch the radiobutton "Robots rule!".
8. Click on the "S... |
num1 = 10
num2 = 20
print(num1 + num2)
for i in range(15)
print(i)
print("c罗牛逼')
jdfj
dfdsd
s
dd
dfsd
ds
sdf
sfd
|
# --> Write a program to count the number of even and odd numbers from a series of numbers.
# -> Sample : numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
# -> Number of even numbers: 5
# -> Number of odd numbers: 4
# Input Format
# 4 1 2 3 4
# Output Format
# 2 -> even count
# 2 -> odd count
n=int(input())
even=[]
odd=[]... |
user = input('请输入用户名: ')
if user == 'zyz':
print('hello, %s' % user)
elif user == 'zzz':
print('hi, %s' % user)
else:
print('您不在我们的系统中,请先注册!同意扣1,不同意扣2')
if int(input())==1:
print('注册连接为:xxxx.xx')
else:
print("一边玩去")
|
import sys
from cs50 import get_string
# Check user if user provided exactly one argument
if len(sys.argv) == 1:
print("You did not enter an argument for the encryption key.")
print("Please restart the program with one non negative integer in the command-line-argument.")
elif len(sys.argv) > 2:
print("Yo... |
#magic methods - implement operator overloading
#special methods - dunder e.g. __init__ , when creating class objects
#BROKEN CODE
def __repr__ (self):
#unambigous representation of object
#debugging and logging for developers
def __str__ (self):
#readable representation to end User
################################... |
from functional import Transform
t = "Expected:{} Given:{} Test:{}"
def run_map():
input_list = [1, 2, 3, 4]
expected_output = ['1', '2', '3', '4']
print_result(expected_output, Transform.map(input_list, lambda x: str(x)))
input_list = [1, 2, 3, 4]
expected_output = ['1'... |
#namedtuple are also similiar to tuple and are immutable
Point =namedtuple('Point',list('abcd'))
new=Point(1,5,1,6)
print (type(new),new)
#printing fields in namedtuple
print (new._fields)
#converting namedtuple to ordereddict
print (new._asdict())
#new._replace to replace the values in namedtuple
print (new._r... |
import random;
import time;
y=time.time();
class SnakesLadders:
p1,p2,k,counter=0,0,0,0;
def __init__(self):
self.Ladders=Ladders={2:38,7:14,8:31,15:26,21:42,28:84,36:44,51:67,71:91,78:98,87:94}
self.Snakes=Snakes={16:6,46:25,49:11,62:19,64:60,74:53,89:68,92:88,95:75,99:80};
def game_over... |
def clasificador():
num=input ("dime un numero")
if num%2==0:
if num%3==0:
print "etiqueta verde"
else:print "etiqueta roja"
else:
if num%3==0:
print "etiqueta amarilla"
else:
print"negro"
clasificador()
|
#se pide un num obtener x pantalla la suma de digitos del numero
def suma():
num=input('dime un num')
cadena=str(num)
longi=len(cadena)
suma=0
for i in range(0,longi,1):
suma=suma+int(cadena[i:i+1])
print suma
suma()
|
# How many seconds in 42 minutes and 42 seconds
ans1 = 42*60+42
print('There are {0} seconds in {1}'.format(ans1,'42 minutes and 42 seconds'))
# How many miles are there in 10 kilometers? 1 mi = 1.61 km
ans2 = 10/1.61
print('There are {0:.3f} miles in {1}'.format(ans2, '10 kilometers'))
# If you run 10 km in 42 min 42 ... |
# Iteration
# 7-1
# Square roots with Newton's method
import math
def sqroot(a,x):
epsilon = 0.0001
y = (x+a/x)/2
if abs(x-y) < epsilon:
return y
else:
x = y
return sqroot(a,x)
def test_square_root():
print('')
dash = '-'*42
for x in range(10):
if x == 0:
... |
for case in range(int(input())):
R, str = input().split()
alphanumeric = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\$%*+-./:"
P = ""
for i in str:
if i not in alphanumeric:
continue
P += i*int(R)
print(P) |
word = input()
chroa = ["c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="]
count = 0
index = 0
check = False
while index<len(word):
check = False
for i in chroa:
if word[index:index+3].find(i) != -1:
count += 1
index = index+len(i)
check = True
break
if check == False:
count += 1
... |
# Priority Queue by deque
# 1 1 9 1 1 1
# 4 2 3 1
for case in range(int(input())):
N, M = map(int, input().split())
print_list = list(map(int, input().split()))
target = print_list[M]
print_order = list()
for i in range(len(print_list)):
if print_list[i] ==
while q:
while ma... |
word = input()
delay = 0
for i in word:
if i == 'S':
delay += 8
continue
elif (ord(i)-ord('A')) >= 19 and (ord(i)-ord('A')) <= 21:
delay += 9
continue
elif (ord(i)-ord('A')) >= 22 and (ord(i)-ord('A')) <= 25:
delay += 10
continue
delay += int((ord(i)-ord('A'))/3.0)+3
print(de... |
S = input()
alpha = "abcdefghijklmnopqrstuvwxyz"
for a in alpha:
print(S.find(a), end=' ') |
class FibonacciNode:
degree = 0
p = None
child = None
mark = False
left = None
right = None
def __init__(self, k):
self.key = k
def __iter__(self):
"""
generate a list of children of the node for iteration
"""
self.children = []
self.inde... |
from typing import Any, Optional
class LinkedListNode:
def __init__(self, key: Any):
self.key: Any = key
self.prev: Optional[LinkedListNode] = None
self.next: Optional[LinkedListNode] = None
class LinkedList:
def __init__(self, key=None):
self.head: Optional[LinkedListNode] =... |
#!/usr/bin/env python
def comparable(a, b, x):
"""
Given two segments a and b that are comparable at x, determine whether a is above b or not. Assume that neither segment is vertical
"""
p1 = a[0]
p2 = a[1]
p3 = b[0]
p4 = b[1]
x4 = p4[0]
x3 = p3[0]
v1 = (p2[0] - p1[0], p2[1] - ... |
#!/usr/bin/env python
# coding=utf-8
def three_sum(array):
"""
Given an array `array` of n integers, find one triplet
in the array which gives the sum of zero.
`array` must be in increasing order
"""
n = len(array)
for i in range(n - 2):
j = i + 1
k = n - 1
while ... |
from unittest import TestCase
from Queue import Queue, EmptyException, FullException
class TestQueue(TestCase):
def test_enqueue_and_dequeue(self):
queue = Queue(3)
queue.enqueue(1)
queue.enqueue(2)
with self.assertRaises(FullException):
queue.enqueue(3)
self.as... |
from Queue import Queue, FullException, EmptyException
class Deque(Queue):
"""
whereas a Queue allows insertion at one end and deletion at the other end,
a Deque(double-ended Queue) allows insertion and deletion at both ends
"""
def __init__(self, size):
super().__init__(size)
def en... |
class FullException(Exception):
pass
class EmptyException(Exception):
pass
class Stack(list):
def __init__(self, size):
super(Stack, self).__init__([None] * size)
self.top = -1
self.size = len(size)
def push(self, x):
if self.full():
raise FullException("... |
from queue import Queue
from graph import Graph, Vertex
def wrestlers(wrestlersList, rivalriesList):
"""
There are two types of professional wrestlers: "babyfaces"
("good guys") and "heels" ("bad guys"). Between any pair of
professional wrestlers, there may or may not be a rivalry.
Given a list of... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def split(text, delimiter):
l = []
tmp = ""
i = 0
while i < len(text):
# print(tmp)
if text[i] != delimiter[0]:
tmp = tmp+text[i]
i += 1
continue
s = True
for j,d in enumerate(delimiter):
if i+j>len(text) or text[i+j] != d:
s = False
break... |
from concurrent.futures import ThreadPoolExecutor, wait, as_completed
from time import sleep
from random import randint
def return_after_5_secs(num):
sleep(randint(1, 5))
return "Return of {}".format(num)
if __name__ == '__main__':
pool = ThreadPoolExecutor(5)
futures = []
for x in range(5):
... |
#!/usr/bin/python
#brute force
import sys
from collections import namedtuple
import random
Item = namedtuple('Item', ['index', 'size', 'value'])
def knapsack_solver(items, capacity):
ratiolist = []
index = []
value = []
size = []
iamtuple = []
for i in range(0, len(items)):
col = [ite... |
count =0
for x in range (1,5):
for y in range(1,5):
for z in range(1,5):
if (x!=y and y!=z and x!=z):
count +=1
print(x*100+y*10+z)
print('共有',count,'个三位数') |
digital = 0
character = 0
other = 0
blank = 0
i=input()
for ch in i:
if (ch >= '0' and ch <= '9'):
digital +=1
elif ((ch >= 'a' and ch <= 'z') or (ch > 'A' and ch <= 'Z')):
character +=1
elif (ch == ' '):
blank +=1
else:
other +=1
print('数字个数:'+str(digital))
print('英文字母个... |
import numpy as np
a =np.zeros((3,3))
print('请输入9个整数:')
for i in range(3):
for j in range(3):
a[i][j]=(float(input()))
sum = 0
for i in range(3):
for j in range(3):
if(i==j):
sum += a[i][j]
print('对角线之和:',sum) |
x = str(input())
def func(x):
x = list(x)
small = 0
big = 0
for y in x:
if y.islower() == True:
small += 1
elif y.isupper():
big += 1
return (small, big)
print(func(x))
|
def ExtractData4rmCSV(csvfilepath):
"""
This function's purpose is to convert a csv file containing signal values into a single dataFrame
"""
import csv
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import datetime
content = []
with ope... |
class Path(object):
#定义Path,每一个Path类代表到达当前step的一个路径,如果是在init位置,path_history为空,则赋值当前step
def __init__(self,step,goal,path_history = None):
self.step = step
#第一个点
if not path_history:
self.path_memory = [step]
else:
self.path_memory = path_history.path_memor... |
"""
Problem 1 - A stock trader wants to trade in securities
that match certain conditions. For some securities,
it would be if it crosses a limit value, for some if
it goes below the limit value (possibly for shorting).
You are given a dictionary of securities and their
limit values and a condition as a dictionary.
T... |
#-*-*-coding: utf-8
## {{{ http://code.activestate.com/recipes/496884/ (r10)
"""
Amaze - A completely object-oriented Pythonic maze generator/solver.
This can generate random mazes and solve them. It should be
able to solve any kind of maze and inform you in case a maze is
unsolveable.
This uses a very simple represe... |
""" Prime number generation """
import random
from itertools import cycle,imap,dropwhile,takewhile
def is_prime(n):
""" Is the number 'n' prime ? """
prime = True
for i in range(2,int(pow(n,0.5))+1):
if n % i==0:
prime = False
break
return prime
def prime_... |
def printMultiplication(dan):
for item in range(1, 10):
result = "{} * {} = {}".format(dan, item, item * dan)
print(result)
for item in range(2, 10):
printMultiplication(item)
print("-------------")
|
import numpy as np
def mean(x):
return np.sum(x)/len(x)
def std(x):
return (np.sum([(x[i]-mean(x))**2 for i in range(len(x))])*1/len(x))**0.5
|
for i in range(10):
if (i < 10 and i > 5):
print(8%3)
else:
print("Unbroken 1")
for i in range(10):
if i == 5:
break
else:
print("Unbroken 2")
|
class HashTables: #these are the implementations of dictionaries by assigning a value to a key
def __init__(self):
self.size = 10
self.keys = [None] * self.size #index all through the bucket
self.values =[None] * self.size #values all through the bucket
def insert(self, ke... |
# FIFO : first in first out
class Queue:
def __init__(self):
self.queue = []
def is_empty(self):
return self.queue == []
# O(1) running time complexity
def enqueue(self, data): #means add data to the queue
self.queue.append(data)
# O(N) running time complexity
def d... |
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to i... |
import math
def shortest_path(graph, start_node, end_node):
if start_node == end_node:
return [start_node]
node_distances = dict()
unvisited = set()
# build our result and unvisited dictionaries
for node in graph.intersections:
cost_to_goal = get_cost_to_goal(graph, nod... |
# Task 1 - Solution
locations = {'North America': {'USA': ['Mountain View']}}
locations['North America']['USA'].append('Atlanta')
locations['Asia'] = {'India': ['Bangalore']}
locations['Asia']['India'].append('New Delhi')
locations['Asia']['China'] = ['Shanghai']
locations['Africa'] = {'Egypt': ['Cairo']}
# Task 2 - S... |
# Recursive Solution
def add_one(arr):
"""
:param: arr - list of digits representing some number x
return a list with digits represengint (x + 1)
"""
# Base case
if arr == [9]:
return [1, 0]
# A simple case, where we just need to increment the last digit
if arr[-1] < 9:
... |
class Node:
def __init__(self, newData, pointer):
self.pointer = pointer
self.data = newData
def getData(self):
return self.data
def changeData(self, data):
self.data = data
def addNode(self, newNode):
self.pointer.append(newNode)
def rmNode(self, index):
del self.pointer[index]
def getXNode(self, ind... |
import math
import torch
from torch import autograd
import torch.nn as nn
class SelfAssessmentFunction(autograd.Function):
"""
Implements two linear layers, one called 'main' and one called 'sass' (for 'self-assessment').
The main layer behaves just like a regular linear layer.
The sass layer behav... |
#!/usr/local/bin/python3
"""
fo=open('newdemo.txt','w')
print(fo.mode)
print(fo.readable())
print(fo.writable())
fo.close()
"""
"""
#if we don't have any file and then we have to open it on write mode
my_content=["This is a data\n""This is a data\n"]
fo=open('newdemo1.txt','w')
#fo.write("This is first line and iam sti... |
#!/usr/local/bin/python3
"""
import os
path=input("Enter your path: ")
if os.path.isfile(path):
print(f"The given path is: {path} is a file")
else:
print(f"The given path is: {path} is a directory")
"""
import os
path=input("Enter your path: ")
if os.path.exists(path):
print(f"Given path: {path} is valid")
if os... |
#!/usr/local/bin/python3
import os
path="/root/python/section10"
print(os.path.basename(path))
print(os.path.dirname(path))
path1="/home"
path2="redhat"
print(os.path.join(path1,path2))
'''
path2="/root/python/section10"
print(os.path.split(path2))
print(os.path.getsize(path2))
print(os.path.exists(path2))
if os.path.e... |
#!/usr/local/bin/python3
"""
num=eval(input("Enter the number: "))
if num==1:
print("one")
if num==2:
print("two")
if num==3:
print("three")
if num==4:
print("four")
if num not in [1,2,3,4,5,6,7,8,9,10]:
print(f"your number is not there in 1-10 range: {num}")
"""
"""
num=eval(input("Enter your number: "))
if num i... |
#!/usr/local/bin/python3
usr_string=input("Enter your string: ")
usr_conf=input("Do you want to convert your string into lower case say yes or no: ")
if usr_conf=="yes":
print(usr_string.lower())
|
#!/usr/local/bin/python3
import os
req_file=input("Enter your filename to search: ")
for r,d,f in os.walk("/"):
for each_file in f:
if each_file==req_file:
print(os.path.join(r,each_file))
|
"""
#This is a simple arithmetic script
a=24
b=27
sum=a+b
print(f"The sum of {a} and {b} is: {sum}")
"""
#This script is all about the arithmetic operations
a=24
b=32
sum=a+b
print(f"The sum of {a} and {b} is: {sum}")
|
import numpy as np
import matplotlib.pyplot as plt
import colorsys
import sys
K = 3 # number of centroids to compute
numClusters = 3 # actual number of clusters to generate
ptsPerCluster = 80 # number of points per actual cluster
xCenterBounds = (-1, 1) # lower and upper limits within which to place actual clust... |
width = int(input("Width of multiplication table: "))
height = int(input("Height of multiplication table: "))
print ("")
# Print the table.
for i in range(1, height + 1):
for j in range(1, width + 1):
print ("{0:>4}".format(i*j), end="")
print ("")
|
import sys
class Stack():
def __init__(self):
self.stack = []
def push(self, num):
self.stack.append(num)
def pop(self):
if self.stack == []:
return -1
else:
return self.stack.pop()
def size(self):
return len(self.stack)
def em... |
test = input().strip()
cnt = test.count(' ')
if test == '':
print(0)
elif cnt == 0:
print(1)
else:
print(cnt+1)
|
year = int(input())
if year%4 ==0 and (year%100 != 0 or year%400 ==0):
print('1')
else:
print('0')
|
N, M, V = map(int,input().split())
matrix = [[0]*(N+1) for _ in range(N+1)]
for _ in range(M):
link= list(map(int,input().split()))
matrix[link[0]][link[1]] = 1
matrix[link[1]][link[0]] = 1
# print(matrix)
def dfs(current_node, row, foot_print):
foot_print += [current_node]
for search_nod... |
textTweet = "#ea5 ahi vamos con todo"
# print (textTweet)
counter = 0
x = 0
while x == 0 :
enterText = input("ingrese su texto: ")
if enterText == str('maquina') :
counter += 1
print (enterText + ' ' + str(counter)) |
# coding: utf-8
import re
napis = "kod pocztowy: 61-695 Poznań"
# .+ przynajmniej jedno wystąpienie dowolnego znaku
#pattern = r".+\d{2}-\d{3}.+"
pattern = r"(?P<kod>\d{2}-\d{3})"
# zwróci cały napis
#print(re.match(pattern, napis))
match = re.search(pattern, napis)
print(match)
print(match.groups())
print(match.... |
"""
"""
import numpy as np
from visualization.graph_visualizer import draw_graph
from visualization.board_visualizer import DrawBoard
class Node:
"""
Board structure:
Every node has up to 8 neighbors, indexed from 0-7 with 0 starting from the
upper left corner then 1..7 moving clockwise
"""
d... |
"""
BREAKS
REQUIRES SETUP - see README
Given the root of a graph, the object that represents a node in the graph, and the output file path, this
algorithm can recursively visualize the nodes and connection in any graph
Created for visualizing trees (e.g. move histories) - not good for densely connected graphs
*This ... |
"""
Build environment with 3D node connections -
top layer - 9 connected nodes
bottom layer - 9 connected nodes for each connected node in the top layer (all connected to top node)
"""
from visualize_graph import draw_trees
class Node:
def __init__(self, id, value):
self.id = id
self.value = valu... |
numbers = {
'Besnik Derda': '+355 555 2356',
'Axel Gera': '+355 444 5487',
'Era Korce': '+355 333 3568'
}
numbers['Besnik Derda'] = '+355 222 1234'
numbers['Anna Derda'] = '+355 111 2327'
print(numbers['Era Korce'])
print(numbers.get('Era Korce'))
for key in numbers: # same as "for key in numbers.keys()... |
from random import randint
n = int(input('Enter the number of rows: '))
m = int(input('Enter the number of columns: '))
matrix = [] # matrix is n x m
for i in range(n):
matrix.append([])
for j in range(m):
matrix[i].append(randint(0, 9))
transpose = [] # transpose is m x n
for j in range(m):
... |
from random import randint
# generates a random number (year) between 1500 and 2020 (inclusive)
year = randint(1500, 2020)
if year > 1548 and (year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)):
print(year, 'is a leap year')
else:
print(year, 'is not a leap year')
|
class Person:
def __init__(self, name, birth_year):
self.name = name
self.birth_year = birth_year
def to_string(self):
print('Person name:', self.name)
print('Birth Year:', self.birth_year)
class Student(Person):
def __init__(self, name, birth_year, major):
super()... |
with open('DNASequence.txt') as file:
file_contents = file.read()
ca = 0
for i in range(len(file_contents)-1):
if file_contents[i:i+2] == 'ca':
ca += 1
print('The sequence ca is repeated {} times.'.format(ca))
|
import sys
def main_file_data_reader(file):
read_lines: int = 0
read_word: int = 0
read_bytes: int = 0
max_line_length: int = 0
file_data = open(file, "r")
for line in file_data:
read_lines += 1
if len(line) > max_line_length:
max_line_length = len(line)
re... |
import math
import random
import sys
from typing import List, Generator
def generate_random_tree(tree_height: int) -> List:
if tree_height < 0:
raise ValueError('tree_height should be a positive number')
upper_limit: int = int(math.pow(2, tree_height))
lower_limit: int = int(math.pow(2, tree_heigh... |
import math
import numpy as np
from math import sqrt
from scipy.stats import norm
class touchscreenEvaluator:
def __init__(self):
self.past_distributions = {}
def calc_score_spherical(self, actual_frame, estimated_frame):
"""
Calculates the accuracy of a frame distribution. It works b... |
#9.4 Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a cou... |
for t in range(int(input())):
n=int(input())
s=input()
if('I' in s):
print("INDIAN")
elif('Y' in s):
print("NOT INDIAN")
else:
print("NOT SURE") |
for t in range(int(input())):
n=int(input())
fact=1
for i in range(1,n+1):
if(n==1 or n==0):
fact=fact*1
else:
fact=fact*i
print(fact) |
for _ in range(int(input())):
n=int(input())
lst=list()
for i in range(n):
x=int(input())
if(x in lst):
lst.remove(x)
else:
lst.append(x)
print(*lst) |
from compare import compare
from number_letter_counts_dict import data, data_num
'''
If all the numbers from 1 to 1000 (one thousand) inclusive
were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens.
For example, 342 (three hundred and forty-two) contains 23 letters
a... |
from compare import compare
from primeFactor import factorisation
'''
#014
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Which starting number, under one million, produces the longest chain?
'''
def next_collatz(n):
if n % 2 == 0:
... |
from compare import compare
from math import sqrt
from time import time
FN = 'primes.txt'
def prime_numbers(max_n):
# не очень удачная реализация вычислялки простых чисел
prime = [2,3]
number = 5
j = 1
while True:
if j == 3:
j = 1
continue
els... |
# First week Tuesday
# Topic Covered
# Classes
# Class Function
# Using of class attrbute
# Public behavior
# Inheritance
# calling function of parent through inheritance OOP concepts
class Book:
def __init__(self, name, pages, author):
self.name = name
... |
# Uses python3
import sys
def fibonacci_last_digit(n):
current = 0
next = 1
for x in range(n):
oldNext = next
next = (current + next) % 10
current = oldNext
return current
if __name__ == '__main__':
#input = sys.stdin.read()
input = "832564823476"
n = int(input) +... |
# This is an implementation of the factorial function
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def main():
print(factorial(5))
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
main() |
x=[1,2,3,4,5,6,7,8,9]
x.remove(x[5] )
print(x[2:7] )# upto the element the last elemtn not including lst element
# use neagtive number to go the end of the list::::::
# use index funtion to print the index value of the list x.index(3)
# use count funtion the no same data in there for ex- x.co... |
def hotel_cost(nights):
return 140*nights
def plane_ride_cost(city):
if city=="Charlotte":
return 183
elif city=="Tampa":
return 220
elif city=="Pittsburgh":
return 222
elif city=="Los Angeles":
return 475
plane_ride_cost("Tampa")
def rental_car_cost(days):
... |
#Dictionaries- a dictionaries consist of keys and value
# we use curly barce to create dictionaary example= dict={}
test={"tushar":18,"parmod":24,"sad":20,"mitul":20}
print(test)
test["lemon"]=30 # to add the info in the dictonries
print(test)
del test["lemon"] # to delete the info in the dict
print(test)
t... |
arr=(2,4,5)
##
##for c1 in range(10):
## for c2 in range(10):
## for c3 in range(10):
## if (c1,c2,c3) == arr:
## print("found the combo: {}".format((c1,c2,c3)))
## break
## print(c1,c2,c3)
##string formating
##for (c1... |
phrase = "A bird in the hand..."
# Add your for loop
for char in phrase:
if char=="A" or char=="a":
print ("X"),
else:
print (char),
def digit_sum(n):
new=0
while(n>0):
r=n%10
n=n//10
new=new+r
return new
print(digit_sum(500))
|
class Matrix:
# grid is a 2D list (maybe should use an array)
grid = []
def __init__(self, height, width):
self.height = height
self.width = width
self.fill_grid() # be optional?, user cast
# fill the matrix with 0 to width * height - 1
def fill_grid(self):
for i... |
from timeit import default_timer as timer
board = [
[0,0,0, 0,3,0, 0,0,0],
[0,0,1, 0,7,6, 9,4,0],
[0,8,0, 9,0,0, 0,0,0],
[0,4,0, 0,0,1, 0,0,0],
[0,2,8, 0,9,0, 0,0,0],
[0,0,0, 0,0,0, 1,6,0],
[7,0,0, 8,0,0, 0,0,0],
[0,0,0, 0,0,0, 4,0,2],
[0,9,0, 0,1,0, 3,0,0]
]
def ... |
import pandas as pd
def multiplyNumbers(numbers, multiplier):
newList = []
for item in numbers:
newList.append(item * multiplier)
return newList
print(multiplyNumbers([1, 2, 3, 4], 10))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.