text stringlengths 37 1.41M |
|---|
#Lewis Travers
#31/10/2014
#Asking for a number between 10 and 20
number = int(input("Please enter a number between 10 and 20: "))
while number <10 or number >20:
print("That is not within the correct range")
if number >10 and number <20:
print("That number is within the correct range.")
|
def distance(v,a):
'''
count the minimum runway length
'''
length=v**2/2*a
print('Minimum runway length is %.2f meters'%length)
if __name__ == '__main__':
v, a = eval(input())
distance(v,a)
|
name = input("What is your SECRET?: ")
while True:
try:
#shifting @ 26, returns the same position
shift = int(input("Number of Caesar shifts?: ")) % 26
except ValueError:
print ("Please input a number!")
continue
else:
break
print('Your SECRET is:', name)
print(... |
List = [3, 7, 7, 4, 6, 1, 12, 10, 0, 7, 7, 9]
print(List)
suma = 0 #for
for i in List:
suma += i
print("Цикл for: ", suma)
i = 0 #while
suma = 0
while i < len(List):
suma += List[i]
i += 1
print("Цикл while: ", suma)
def suma(numbers): #рекурсія без збереження даних
if len(numbers) == 1:
return numbers[0]
els... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 4 20:11:18 2019
@author: Josh
"""
import numpy as np
from chip_class import Chip
from lines_class import Lines
import random
import copy
import math
class Board(Lines):
'''
A Board object contains:
- The size of t... |
import tkinter
from PIL import Image,ImageTk
root=tkinter.Tk()
root.geometry("1300x244")
photo=tkinter.PhotoImage(file='logo1.png')
#FOR JPG IMAGES
# image=Image.open("shoe.jpg")
# photo=ImageTk.PhotoImage(image)
label=tkinter.Label(image=photo)
label.pack()
root.mainloop() |
# %%
def problem1_7():
b1 = float(input("Enter the length of one of the bases: "))
b2 = float(input("Enter the length of the other base: "))
h = float(input("Enter the height: "))
if b1 == b2:
A = b1*h
else:
A = ((b1+b2)/2)*h
print("The area of a trapezoid with bases", b... |
import torch
dtype = torch.float
device = torch.device("cpu")
N, D_in, H, D_out = 64, 1000, 100, 10
x = torch.randn(N, D_in, device=device, dtype=dtype)
y = torch.randn(N, D_out, device=device, dtype=dtype)
w1 = torch.randn(D_in, H, device=device, dtype=dtype, requires_grad=True)
w2 = torch.randn(H, D_out, device=d... |
Name = input("Enter name: ")
Age = input ("Enter age: ")
Address = input ("Enter adress: ")
print(f'Hi, my name is {Name}. I am {Age} years old and I live in {Address}.') |
"""
# ----------- Linear Regression. ----------- #
# Import and create the model.
from sklearn.linear_model import LinearRegression
your_model = LinearRegression()
# Fit.
your_model.fit(x_training_data, y_training_data)
# Predict.
predictions = your_model.predict(your_x_da... |
# --------------- Codecademy. --------------- #
# #
# PATH: Computer Science. #
# TRACK: Python Fundamentals. #
# LESSON: Code Challenge: Loops. #
# #
# --------------- Codecademy. --... |
# --------------- Codecademy. --------------- #
# #
# PATH: Machine Learning. #
# TRACK: Supervised Learning: Regression. #
# LESSON: Distance Formula. #
# #
# --------------- Codecademy. --... |
import random
def takechoice():
print(random.randint(1, 6))
choice = input("Want to roll again?")
if choice == "yes" or choice == "Yes" or choice == "y" or choice == "Y":
takechoice()
takechoice()
|
class InvalidDimensionError():
''' An error to be raised when a dimension of a matrix which does not
exist is trying to be accessed.'''
pass
class MathError():
''' An error to be raised when doing math operations on incompatable types.
i.e(adding a string to an integer).'''
pass
... |
'''
문제 2.
자연수 N이 주어졌을 때, 1부터 N까지 한 줄에 하나씩 출력하는 프로그램을 작성하시오.
'''
numbers = int(input('숫자를 입력하세요: '))
# 아래에 코드를 작성해 주세요.
for num in range(numbers+1):
print(num)
# 정답
for i in range(numbers+1):
print(i+1) |
def reverseList(list):
if (len(list) == 1):
return list
return reverseList(list[1:]) + list[0:1]
list = [1, 2, 3, 4, 5]
print(reverseList(list))
def reverseStr(str):
if (str == ''):
return ''
return reverseStr(str[1:]) + str[0]
str = 'hello world'
print(reverseList(str)) |
# Instructions
"""
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Credits:
Special thanks to @ts for adding this problem and creating all test ... |
# Instructions
"""
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note: All inputs will be in lower-case.
"""
import collections
class Solution(object):
# def groupStrings(self, st... |
"""
Your task is to make a function that can take any non-negative integer as a argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.
Examples:
Input: 21445 Output: 54421
Input: 145263 Output: 654321
Input: 1254859723 Output: 9875543221
... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# def isSameTree_PRACTICE(self, p, q):
def isSameTree(self, p, q):
return
def isSameTree_PASSED(self, p, q):
# def isSameTre... |
import sys
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
walk = head
... |
def main():
list = [9, 3, 6, 19, 5, 22, 4, 295, 28, 55]
list = [6,
31415926535897932384626433832795,
1,
3,
10,
3,
5,]
print("sorted: {}".format(selection_sort(list)))
print()
# comparisons: 45
# swaps: 9
def selection_sort(list):
... |
def construct_pascals_trigangle(n):
"""
construct_pascals_trigangle - builds a Pascal triangle n levels in height
:param n: height of triangle
:return: 2d array-list containing completed triangle
"""
retval = [[1], [1, 1]]
for i in range(1, n-1):
new_row = build_row(retval[i])
... |
#!/usr/bin/python3
from tree_node import Node
from binary_tree import *
import sys
def main():
root = Node(data=1)
root = add_right(2, root)
root.right = add_right(5, root.right)
root.right.right = add_right(6, root.right.right)
root.right.right = add_left(3, root.right.right)
root.right.right.... |
# Instructions
"""
Related to question Excel Sheet Column Title
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
"""
class Solution(object):
def titleToNumber(self, s):
"... |
"""
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
"""
from data_structures.binar... |
import sys
from sgk_test import test
# Instructions
"""
You are given two non-empty linked lists representing two
non-negative integers. The digits are stored in reverse
order and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
You may assume the two numbers do not conta... |
from collections import defaultdict
class TrieNode:
def __init__(self):
self.children = defaultdict(TrieNode)
self.is_end_of_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
walk = self.root
for c in word:
if c... |
# Instructions
"""
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
"""
class Solution(object):
# def hammin... |
"""
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees m... |
# Instructions
"""
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
"""
class Solution:
# def trap_PRACTICE(self, height):
def trap(self, height):
... |
import sys
comps = 0
inserts = 0
shifts = 0
class Sort():
# global comps, inserts, shifts
def __init__(self):
self.shifts = 0
self.comps = 0
self. inserts = 0
def insertion_sort(self, list, new_elem=None):
size = len(list)
i = 1
if size < 2 or (size == 2 a... |
"""
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
Given target value is a floating point.
You are guaranteed to have only one unique value in the BST that is closest to the target.
"""
from data_structures.binary_search_tree import *
from data_... |
def lt_gt_eq (item1, item2):
if type(item1) is not int or type(item2) is not int:
raise TypeError("Arguments must be integers")
if item1 < item2:
return "Less Than"
if item1 > item2:
return "Greater Than"
return "Equal"
from os.path import isfile, exists
def populate_director... |
"""
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
Now given an M x N matrix, return True if and only if the matrix is Toeplitz.
Example 1:
Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: True
Explanation:
1234
5123
9512
In the above grid, the diagonals are "[9]"... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None or root == [] or root... |
# Instructions
"""
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters?... |
"""
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
Example:
For num = 5 you should return [0,1,1,2,1,2].
Follow up:
It is very easy to come up with a solution with run time O(n*sizeof(intege... |
# Instructions
"""
Numbers can be regarded as product of its factors. For example,
8 = 2 x 2 x 2;
= 2 x 4.
Write a function that takes an integer n and return all possible combinations of its factors.
Note:
You may assume that n is always positive.
Factors should be greater than 1 and less than n.
Examples:
input: ... |
"""
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
One po... |
# Instructions
"""
Implement a method to peroform basic string compression using the counts of repeated chatracters. For example, the string 'aabcccccaaa' would become 'a2b1c5a3'. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assum... |
# 337. House Robber III
"""
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will auto... |
"""
A flock of n birds is flying across the continent. Each bird has a type, and the different types are designated by the ID numbers 1, 2, 3, 4, and 5.
Given an array of n integers where each integer describes the type of a bird in the flock, find and print the type number of the most common bird. If two or more type... |
def centuryFromYear(year):
# if year < 100:
# return 1
next = False
if year % 100 != 0:
next = True
retval = year // 100
if next:
return retval+1
return retval
def test(retval, sol):
if retval != sol:
print("FAIL: ")
print(f"retval: {retval}")
... |
#!/usr/bin/python3
import sys
def birthdayCakeCandles(n, ar):
# Complete this function
tallest = max(ar)
count = ar.count(tallest)
return count
n = 4
string = '3 4 5 5 5 4 3 2 5'
ar = list(map(int, string.strip().split(' ')))
result = birthdayCakeCandles(n, ar)
print(result)
|
"""
Well met with Fibonacci bigger brother, AKA Tribonacci.
As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next. And, worse part of it, regrettably I won't get to hear non-native Italian speakers trying to pronounce it ... |
"""
A friend of mine takes a sequence of numbers from 1 to n (where n > 0).
Within that sequence, he chooses two numbers, a and b.
He says that the product of a and b should be equal to the sum of all numbers in the sequence, excluding a and b.
Given a number n, could you tell me the numbers he excluded from the sequen... |
"""
Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.
Example 1:
Input: [2,2,3,4]
Output: 3
Explanation:
Valid combinations are:
2,3,4 (using the first 2)
2,3,4 (using the second 2... |
# Instructions
"""
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
Note: The length of path between two nodes is represented by the number of edges between them.
Example 1:
Input:
5
/ ... |
import csv
with open('emp.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
if((row[0]) != ""):
if ((row[1]) != ""):
if ((row[2]) != " "):
print(row[0], row[1], row[2])
file.close()
|
class Provider(object):
<<<<<<< HEAD
def __init__(self, name, time, resources):
self.name = name
self.time = time
self.resources = resources
def offer(self):
return Offer(self, self.time, self.resources)
def __str__(self):
return self.name
=======
# The provider... |
from functools import cmp_to_key
def compare_func(a, b):
value1, value2 = a + b, b + a
if value1 > value2:
return 1
elif value1 < value2:
return -1
else:
return 0
def solution(numbers):
n = [str(num) for num in numbers]
n = sorted(n, key=cmp_to_key(compare_func), reve... |
import sys
from datetime import datetime
n = int(input())
min_value = sys.maxsize
min_name = ''
max_value = -sys.maxsize
max_name = ''
for _ in range(n):
name, day, month, year = input().split(" ")
day, month, year = int(day), int(month), int(year)
seconds = datetime.strptime(
"{}-{}-{}".format(y... |
N = int(input())
nums = [1] * (N + 1)
nums[0] = 0
nums[1] = 0
primes = []
for i in range(2, N + 1):
if nums[i]:
primes.append(i)
for j in range(2 * i, N + 1, i):
nums[j] = 0
answer = 0
for i in range(len(primes)):
for j in range(i + 1, len(primes) + 1):
sum_value = sum(pri... |
num = int(input())
word_dict = {}
max_len = 0
for _ in range(num):
word = input()
if max_len < len(word):
max_len = len(word)
if len(word) in word_dict.keys():
word_dict[len(word)].add(word)
else:
word_dict[len(word)] = {word}
for i in range(1, max_len + 1):
if word_dict.... |
clock_number_set = set()
def check_clock_number(str_lst):
clock_number = int(''.join(str_lst))
for _ in range(3):
str_lst = [str_lst.pop()] + str_lst
comp = int(''.join(str_lst))
if clock_number > comp:
clock_number = comp
return clock_number
def ma... |
string = input()
target = input()
string_len = len(string)
target_len = len(target)
i = 0
answer = 0
while i < string_len:
if i + target_len <= string_len:
sub_string = string[i:i + target_len]
if sub_string == target:
answer += 1
i = i + target_len
else:
... |
S = input()
T = input()
for _ in range(len(T) - len(S)):
value = T[-1]
T = T[:len(T) - 1]
if value == 'B':
T = T[::-1]
if S == T:
print(1)
else:
print(0) |
def is_possible(one_list, max_size, size):
criteria = 0
passport = 0
for ix, el in enumerate(one_list):
if passport > 0:
passport -= 1
continue
elif passport == 0:
criteria = el
continue
if el == criteria:
continue
... |
tries = int(input())
change_list = [50000, 10000, 5000, 1000, 500, 100, 50, 10]
for i in range(1, tries + 1):
price = int(input())
nums = []
for change in change_list:
if price >= change:
nums.append(str(price // change))
price = price % change
else:
nums... |
tries = int(input())
for t in range(1, tries + 1):
angle = int(input())
total_minutes = angle * 2
hour = total_minutes // 60
minute = total_minutes % 60
print('#{} {} {}'.format(t, hour, minute))
|
import unittest
from src.BinarySearch import binary_search, searchInsert
class BinarySearchTest(unittest.TestCase):
def test_binary_search(self):
self.assertEqual(binary_search([1, 2, 4], 4), 2)
self.assertEqual(binary_search([1, 2, 4], 2), 1)
self.assertEqual(binary_search([1, 2, 4], 1), ... |
def isPalindrome(x: int) -> bool:
if x < 0:
return False
num = str(x)
i = 0
j = len(num) - 1
while i <= j:
if num[i] != num[j]:
return False
i += 1
j -= 1
return True
def isPalindrome_Optimize(x: int) -> bool:
return str(x) == str(x)[::-1]
|
#################################################################
## Home Assignment - 4 ##
## Name: Steven Glasford
## Due Date: April 29 (Wednesday), 11.59 in Blackboard
## Type your answers in this python file and submit in blackboard.
#################################################################
#####... |
#!/usr/bin/env python
def factorial(n):
"""Calcula el factorial de un número"""
resultado = 1
for i in range(1,n+1):
resultado*=i
return resultado
if __name__ == '__main__':
print(factorial(6)) |
#!/usr/bin/env python
def calcular_segundos(horas,minutos,segundos):
return horas*3600+minutos*60+segundos
def calcular_horas(segundos):
horas = segundos // 3600
segundos-=horas*3600
minutos = segundos // 60
segundos-=minutos*60
return horas,minutos,segundos
def calcular(*args):
if len(args)==1:
return calc... |
class circulo():
def __init__(self,radio):
self.radio=radio ## Este el setter
@property
def radio(self):
print("Estoy dando el radio")
return self._radio
@radio.setter
def radio(self,radio):
if radio>=0:
self._radio = radio
else:
raise ValueError("Radio positivo")
self._radio=0
@radio.del... |
#!/usr/bin/env python
import csv
def LeerPartidos():
"""Función que lee el fichero CSV y devuelve los datos del mismo en una
lista de diccionarios con los datos de la liga."""
datos=[]
keys=["fecha","equipo1","equipo2","final","mitad"]
fichero = open("liga.csv")
contenido = csv.reader(fichero)
for row in list(c... |
#!/usr/bin/env python
def operar(n1,n2,*,operador='+',respuesta='El resultado es '):
if operador=="+":
return respuesta+str(n1+n2)
elif operador=="-":
return respuesta+str(n1-n2)
else:
return "Error" |
import math
sumar = lambda a,b: a+b
restar = lambda a,b: a-b
multiplicar = lambda a,b: a*b
dividir = lambda a,b: a/b if b!=0 else print('Numero 0 no es valido')
potenciar = lambda a,b: math.pow(a,b) |
def exec(operation):
while True:
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print('Invalid input')
else:
operation(num1, num2)
break
def division_op... |
def merge(list1, list2, key):
"""
Merges sorted lists, producing a new sorted list. Returns merged list and
inversion count.
"""
result = []
inversion_count = 0
i1 = i2 = 0
while True:
if i1 == len(list1):
result.extend(list2[i2:])
return result, inversion... |
import sys
conversion = {"0000": "11110", "0001": "01001", "0010": "10100", "0011": "10101",
"0100": "01010", "0101": "01011", "0110": "01110", "0111": "01111",
"1000": "10010", "1001": "10011", "1010": "10110", "1011": "10111",
"1100": "11010", "1101": "11011", "1110": "11100... |
n1=int(input("dati numarul primului elevul:"))
p1=int(input("dati puncatjul primului elev:"))
n2=int(input("dati numarul al doilea elev:"))
p2=int(input("dati puncatjul al doilea elev:"))
n3=int(input("dati numarul al treilea elev:"))
p3=int(input("dati puncatjul al treilea elev:"))
if p1>p2 and p1>p3:
print... |
class Item:
def __init__(self, name, lore):
self.name = name
self.lore = lore
def __str__(self):
return f'⚔️ Name: {self.name}, Lore: {self.lore}'
def on_take(self):
print("You have discovered " + self.name)
def on_drop(self):
print("You have discarded" + self.... |
# -*- coding: utf-8 -*-
import numpy as np
def sort_list_pairs(list1, list2, **kwargs):
"""
Sort numeric list according to values in a second array.
This function orders the values in `list2` according to the values passed
as `list1`. The contents can be every sortable format.
Code adapted from ... |
print(' Jogo da Velha \n\n')
jog1 = input('Escolha o caracter para o jog 1(x ou o) ')
while jog1 != 'x' and jog1 != 'o' and jog1 != 'X' and jog1 != 'O':
print('ERRO!opção digitada não é valida!')
jog1 = input('Escolha a opção para o jog 1(x ou o) ')
if jog1 == 'x' or jog1 == 'X':
... |
# BY USING LAMBDA
#INPUT AS "trapizoidal (lambda x : function)"
def trapizoidal(func):
a = float(input("Enter Lower Limit : "))
b = float(input("Enter Upper Limit : "))
n = int(input("Enter the value of 'n': "))
h = (b-a)/n
init = func(a)
final = func(b)
middle_values =0
for i... |
student ={
'male':['Mauro','Greg','Zack'],
'female':['Mariana','Mare','Marta','Paula']
}
for key in student.keys():
for name in student[key]:
if 'M'in name:
print(name)
|
'''Write a Python program to count the number of strings where the string length is 2 or more and
the first and last character are same from a given list of strings. Go to the editor
Sample List : ['abc', 'xyz', 'aba', '1221']'''
lst = ['abc', 'xyz', 'aba', '1221', 's09xs', 'kio']
count = 0
for i in range(len(lst))... |
# print all even numbers
import math
n = int(input("Enter a number: "))
for n in range(1, math.floor(n/2)+1):
print(2*n, end=',')
|
#Movie recommendation system using jaccard distances
dataset = {
"action" : ["matrix","batman","superman","dabang","avengers","thor",
"hulk","krrish","ironman",'kgf','raw','lucy'],
"comedy" : ["the mask","dhamaal","bala","housefull","golmaal",
"hera pheri","golmaal 2","dhamaal 2"... |
#!/usr/bin/env python3
'''
A convenience script to extract a single named column from a CSV file.
Usage: ./csv_helpers.py path/to/file.csv column_name
Author: Yotam Gingold <yotam@yotamgingold.com>
Home: https://github.com/yig/mturk.py
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/pub... |
class Czlowiek(): # klasy mają wskazywać na obiekty
def __init__(self, argX, argY, argZ):
self.pozycReki = 1
self.x = argX
self.y = argY
self.z = argZ
self.kierunek = 1
self.ruchReki = argX
def witaj(self, stopnie):
if self.pozycReki >= 30 or sel... |
#Complete the function to return how many hrs and min are displayed on the 24th digital clock.
def digital_clock(n):
hours = n//60
minutes = n%60
return hours, minutes
#Invoke the function with any interger (seconds after midnight)
print(digital_clock(150))
|
def f(l):
l = l.strip().split(',')
print(l)
print(tuple(l))
print(f(input("numbers separated by come please noob:"))) |
# Your code here
def compute_factorial (n):
result = 1
for i in range(2,n+1):
result *= i
return result
print(compute_factorial(8))
print(compute_factorial(1))
print(compute_factorial(0)) |
LETTERS = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','ñ','o','p','q','r','s','t','u','v','w','x','y','z']
def islower(c):
if c in LETTERS: return True
else: return False
def isupper(c):
if c not in LETTERS and islower(c.lower()): return True
else: return False
d={"upper":0, "lower":0}
d... |
import s5005662_Assignment_Server2.received_files.decoder as dCR
def decode_text():
decode_me_file = open("s5005662_Assignment_Server2/received_files/decode_me.txt", "r")
coded_text = decode_me_file.read()
print ""
print "The coded message in decode_me is: {}".format(coded_text)
decoded_text = dCR... |
import nn
class PerceptronModel(object):
def __init__(self, dimensions):
"""
Initialize a new Perceptron instance.
A perceptron classifies data points as either belonging to a particular
class (+1) or not (-1). `dimensions` is the dimensionality of the data.
For ex... |
class man:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
class coworkers(man):
def __init__(self, name, age, gender, position):
# super()내장함수 부모클래스를 가지고 있는 함수(변수)를 호출
super().__init__(name, age, gender)
se... |
'''
Functions to work with the saved glossary text file
Assumes format: key\tvalue\n
'''
def create_dictionary(filename):
d = {}
with open(filename, 'r') as file:
lines = file.readlines()
for line in lines:
key, value = line.split('\t')
d[key] = value
return d
def ... |
#!/usr/bin/python
#!encoding: UTF-8
import sys
import math
PI35DT = 3.1415926535897931159979634685441852
def calcular_pi (n):
sumatorio=0.0
ini=0
intervalos=1.0/float(n)
for i in range(n):
x_i=((i+1) - 1.0/2.0)/n
fx_i=4.0/(1.0 + x_i*x_i)
ini+=intervalos
sumatorio+=fx_i
valor_pi=sumatorio/n
... |
def checkPalindrome(word):
word = word.lower()
word = word.replace(' ', '')
lenOfOriginalWord = len(word)
if lenOfOriginalWord == 0:
return False
remainder = 1
if lenOfOriginalWord % 2 == 0:
remainder = 0
while len(word) != remainder:
firstCharacter = word[0]
... |
#!/usr/bin/python
"Helpers for Assignment 3."
logfile = None
def open_log(filename):
global logfile
logfile = open(filename, "w")
def write_entry(logstring):
global logfile
# Prints out an entry to the log file
logfile.write(logstring + "\n")
print logstring
def next_entry():
global... |
"""
找出所有水仙花数
Version: 0.1
Author: liyun
"""
for num in range(100,1000):
low = num % 10
mid = num // 10 % 10
hig = num // 100
if num == low **3 + mid ** 3 + hig ** 3:
print(num) |
y = int(input())
y = int(y*1.08)
if(y>206):
print(":(")
elif(y==206):
print("so-so")
else:
print("Yay!")
|
from functions import factorial,fact
# print(factorial(5))
# print(list(map(factorial,range(6))))#map 高阶函数
# print([fact(n) for n in range(6)]) # 列表推导式
filter_list=filter(lambda x:x%2,list(range(6)))
# print(list(filter_list))
# print(list(map(factorial,filter(lambda n:n%2,list(range(6))))))
print([factorial(n) for ... |
richter = float(input("Enter magnitude of earthquake in ritcher scale: "))
energy_released = 10 ** ((1.5 * richter) + 4.8)
tnt_equivalent = energy_released / (4.184 * (10 ** 9))
print("The energy released is {} Joules which is equivalent to explosion of {} tons TNT.".format(energy_released, tnt_equivalent))
|
string = input("Enter the string to check for palindrome: ")
def checkPalindrome(String):
return String == ''.join(list(reversed(list(String))))
print(checkPalindrome(string))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.