text
stringlengths
37
1.41M
""" Project Euler Problem 4 ======================= A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99. Find the largest palindrome made from the product of two 3-digit numbers. """ def ispalindrome(n): ''' return True...
totalArea = 0 while True: try: (x,y,z) = [int(x) for x in raw_input().split('x')] except EOFError: break area = 2 * ((x*y)+(x*z)+(y*z)) smallestSideArea = (x*y*z) / (max(x,y,z)) totalArea += area + smallestSideArea print totalArea
def creersuite(nb): fibo = [0,1] for i in range(2,nb+1): fibo.append(fibo[i-2]+fibo[i-1]) return fibo def afficher(nb,fibo): if nb>=len(fibo): fibo = ajouter(nb,fibo) print "U" , nb , " = " , fibo[nb] def ajouter(nb,fibo): for i in range(len(fibo),nb+1): fibo.append(fibo[i-2]+fibo[i-1]) retu...
# -*- coding: utf-8 -*- """ Created on Fri Nov 1 17:15:51 2019 @author: Farhan Shakil Course: Python Programming Language Roll # PY01052 Email: mfarhanshakil@gmail.com Assignment # 1 Question # 4 Python Program to Calculate Area of a circle using Radius Input """ from math import pi ...
#!/usr/bin/python3 sentence = "this is a pen" words = sentence.split(" ") for word in words: print(word) print(" ||| ".join(words))
#!/usr/bin/python3 my_list = [1, 2, 4, 8, 16] my_list.append(32) print(len(my_list)) print(my_list[3]) print("") for value in my_list: print(value)
import pytz,datetime def time(): if 'おはようございます' == input(): print('おはようございます!今日も一日頑張りましょう!') if '頑張ります' == input(): tz = pytz.timezone("Asia/Tokyo") t1 = datetime.datetime.now(tz=tz) print('いってらっしゃい!' + str(t1)) else: print('頑張りますは?挨...
#!/usr/bin/env python3 def triple(a): return a * 3 def square(b): return b ** 2 def main(): for i in range(1,11): t_result = triple(i) s_result = square(i) if (s_result > t_result): break else: print(f"triple({i})=={t_result} square({i})=={s_result}...
#!/usr/bin/env python3 import sys def file_count(filename): char_count = 0 word_count = 0 line_count = 0 with open(filename, "r") as f: for line in f: word_lst = line.split() word_count += len(word_lst) char_count += len(line) line_count += 1 ...
#!/usr/bin/env python3 def detect_ranges(L): l1 = sorted(L) prev = min(L) lst = [] minimum = 0 for number in l1: if number != prev+1: lst.append(number) elif type(lst[-1]) is tuple: lst[-1] = (minimum, number + 1) else: lst[-1] = (prev, n...
#!/usr/bin/env python3 import pandas as pd def growing_municipalities(df): new_df = df["Population change from the previous year, %"] #get the length of the total number of municipalities num_municipalities = len(new_df) #get the length of municipalities with growing population newer_df = df[df["P...
#!/usr/bin/env python3 def main(): [print((i,j)) for i in [1,2,3,4,5,6] for j in [1,2,3,4,5,6] if i+j == 5] if __name__ == "__main__": main()
#mainReal.py #Aaryan & Feeda #2D portal game. It's like a platformer with portals ##############################Features#################################################### #Portal gun can teleport player #Vector is maintained (force into portal can translate into whatever direction) #Pretty loading screen with moving...
#! -*- encoding: utf-8 -*- import sqlite3 from typing import List, Tuple import sys HELP = """ This script calculates the shortest distance between two stations depends on data in railroads.db Make sure the railroads.db is in the same directory with script Make sure the railroads.db contains data from Kni...
#Minecraft Pig: Each tile is 20 x 20 , use the turtkle to draw the tile # the x and y coordinates of the upper left corner of the tile, and the color in use. import turtle window = turtle.Screen() window.bgcolor("gray") def create_tile(tile_color): new_tile = turtle.Turtle() new_tile.hideturtle() new_tile....
import turtle import random window = turtle.Screen() line = turtle.Turtle() width = window.window_width() height = window.window_height() def draw_line(drawing_turtle, x, y, distance): drawing_turtle.penup() drawing_turtle.goto(x, y) drawing_turtle.pendown() drawing_turtle.forward(distance) x = -wid...
import turtle length = int(input("Enter a number between 50 and 500: ")) window = turtle.Screen() window.bgcolor("gold") plus = turtle.Turtle() plus.pensize(20) plus.color("blue") #1 """plus.forward(length / 2) plus.backward(length) plus.forward(length / 2) plus.right(90) plus.forward(length / 2) plus.backward(length)"...
import math def is_prime(number): for test in range (2, int(math.sqrt(number))+ 1): if number % test == 0: return False return True for i in range (1, 51): print(i, is_prime(i))
# Given nums = [2, 7, 11, 15], target = 9, # Because nums[0] + nums[1] = 2 + 7 = 9, # return [0, 1]. array = [2, 7, 11, 15] target = 9 # O^2 quadratic def sumIndex(array, target): for i in range(len(array)): for j in range(i + 1, len(array)): if (array[i] + array[j] == target): ...
###################################### # Task2 # Напишите рекурсивную функцию для вычисления числа # Фибоначи ###################################### def Fibonacc(count = 10, lastnum = 0, num = 1): print(lastnum, end=", ") count -= 1 if count <= 0: return Fibonacc(count, num, lastnum + num ) co...
########################################### # Task 7 # Дана следующая функция y=f(x): # y = 2x – 10, если x > 0 # y = 0, если x = 0 # y = 2 * |x| – 1, если x < 0 # Найти значение функции по x, который вводиться с клавиатуры x = int(input("Введите число: ")) if x > 0: y = 2 * x - 10 print("Значение функции y =...
############################################ # Task7 # Реализовать логику Union для двух списков (list), # проверить работу алгоритма на set.union ############################################ import random def Difference(set1, set2): differenceSet = set() for s1 in set1: if s1 not in set2: ...
class Course: """Course class""" def __init__(self, name, description, date_of_start_course, date_of_end_course, lessonCount): """Course constructor""" self.name = name self.description = description self.students = [] self.date_of_start_course = date_of_start_course ...
class Person: """Person class""" def __init__(self, name, age): """Person constructor""" self.name = name self.age = age def __str__(self): """Converting class to string""" return f"{self.name}, age: {self.age}"
from google import search import os.path def main(search_term,amount): print "The results will now be printed and saved to a text file named results.txt in the directory of this python script\n" for url in search(search_term, stop=amount): print(url) if os.path.isfile('results.txt'): txt2 = open("results.txt...
import logging logger = logging.getLogger('ParkingLot') class Heap: def __init__(self): self.heap_arr = [] def __str__(self): return str(self.heap_arr) def insert(self, value): self.heap_arr.append(value) if len(self.heap_arr) == 1: return current_ind...
import sys for index in range(len(sys.argv)): if sys.argv[index] == '_': sys.argv[index] = input("Enter a word") sys.argv.pop(0) result = ' '.join(sys.argv) print(result) print( sys.argv)
from Task import task # this is how you import a class from different file def merge(TaskList, first_Index, mid_Index, last_Index): first1 = first_Index last1 = mid_Index first2 = mid_Index + 1 last2 = last_Index tempList = list() index = first1 while (first1 <= last1 and first2 <=...
#! /usr/bin/dev python # -*- coding:utf8 -*- #def make_gray(rgb): return [int(0.299*rgb[0] + 0.587*rgb[1] + 0.114*rgb[2])]*3 grayscale = lambda rgb: [int(0.299*rgb[0] + 0.587*rgb[1] + 0.114*rgb[2])]*3 if __name__ == '__main__': print grayscale((46,113,45));
#11651 #좌표 정렬하기 2 z=[] for i in range(int(input())): z.append(list(map(int, input().split()))) z = sorted(z, key = lambda x : (x[1], x[0])) for i in range(len(z)): print('{} {}'.format(z[i][0], z[i][1]))
#11720 #N개의 숫자가 공백 없이 쓰여있다. 이 숫자를 모두 합해서 출력하는 프로그램을 작성하시오. a = int(input()) b = input() sum = 0 for i in range(a): sum = sum + int(b[i]) print(sum) ''' list1=[] n=(input()) list1=list(map(int,input())) print(sum(list1)) '''
#2941 #예전에는 운영체제에서 크로아티아 알파벳을 입력할 수가 없었다. 따라서, 다음과 같이 크로아티아 알파벳을 변경해서 입력했다. alpha = ['c=','c-', 'dz=', 'd-','lj','nj', 's=', 'z='] i = input() for k in alpha: i = i.replace(k, '!') print(len(i))
#!/usr/bin/env python3 # https://codewithmosh.com/courses/423295/ import os # to clear the screen! os.system("clear") x = 10 y = 11 def printing(): print("\nprint X and Y") print(x, y) printing() print("\nUnpacking a tuple : x, y = y, x / similar to x, y = (y, x)") x, y = y, x printing()
#!/usr/bin/env python3 # https://codewithmosh.com/courses/423295/ print("\nnumbers.sort:") numbers = [4, 1, 41, 4, 99, 22] print(numbers) print(numbers.sort()) print(numbers) print("\nreinitialise and use sorted():") numbers = [4, 1, 41, 4, 99, 22] print(numbers) print(sorted(numbers)) print(sorted(numbers, reverse=T...
#!/usr/bin/env python3 # https://codewithmosh.com/courses/423295/ from array import array import os # to clear the screen! os.system("clear") values = [] for x in range(5): values.append(x * 2) print(values) print("\nUsing List Comprehension:") values = [x * 2 for x in range(5)] print(values) print("\nUsi...
from axelrod.actions import Actions, flip_action, Action from axelrod.player import Player from axelrod.random_ import random_choice C, D = Actions.C, Actions.D class Negation(Player): """ A player starts by cooperating or defecting randomly if it's their first move, then simply doing the opposite of the...
''' This follows from Game of Thrones - I. Now that the king knows how to find out whether a given word has an anagram which is a palindrome or not, he encounters another challenge. He realizes that there can be more than one palindrome anagrams for a given word. Can you help him find out how many palindrome anagrams...
# create some data member a = 1 b = int(input("Masukkan angka pada a : ")) while a < b: print(a) if a > b: break a += 1 # kelipatan 1
# aritmatika dengan user input # pengurangan a = int(input("Masukkan angka [1]: ")) b = int(input("Masukkan angka [2]: ")) hasil = a - b print(a,"-", b,"=", hasil) print("") # penjumlahan a = int(input("Masukkan angka[1]: ")) b = int(input("Masukkan angka[2]: ")) total = a + b print(a, "+" ,b,"=", total) # perkalian...
#def test(): # fib = [i**2 for i in range (10) if i**2 %2 == 0] #fib = [i+(i-1) for i in range(6)] # print(fib) def floor(num): return int(num) def ceil(num): if num > int(num): return int(num+1) else: return int(num)
import re from chessboard import ChessBoard ''' Every chess tournament has at least one arbiter / tournament director to manage the play, rule on disputes, and ensure a successful event. an arbiter has four main responsibilities: 1.Ensure that laws of chess (rules) are followed 2.Prevent cheating 3.Act i...
## En este script puedes encontrar funciones para leer, modificar e imprimir matrices (y otras cosas) from random import randint # Leer una matriz nxm elemento a elemento a partir de la entrada estándard def lee_matriz(n, m): M = [] for i in range(0, n): fila = [] for j in range(0, m): ...
#Table Function def TableFunction(NestedList): for item in NestedList: print("| {0:<12} | {1:<5} |".format(item[0], item[1])) def findWidth(NestedList,column): width = 0 for item in NestedList: if len(item[column]) > length: length = len(item[column]) return leng...
""" This model illustrates the spontaneous synronization of large crowds without a central central clock or synronization tool. In this model, the agents (fireflies) start chaning color (blinkin) at random frequencies. However, at each simulation run, the agents increase or decrease the frequencies based on the average...
from typing import List def find_second_min(nums: List[int]) -> int: """Finds the second minimum element of an array""" first = second = float('inf') # Sentinel value as inf is always greater for num in nums: if num <= first: first, second = num, first elif num < second: ...
class ListNode(): def __init__(self, x): self.val = x self.next = None def remove_nth_from_end(head: ListNode, n: int) -> ListNode: """Removes nth node from end of linked list""" node = head queue = [] while node.next: if len(queue) < n: queue.append(node) ...
from typing import List # 0 - fruit type 1 # 1 - fruit type 2 # 2 - fruit type 3 # 3 - fruit type 2 # 4 - fruit type 2 def fruit_into_baskets(tree: List[int]) -> int: fruit_pairs = tree[:2] max_pair_count = 0 current_pair_count = 0 for index, fruit_type in enumerate(tree): if fruit_type in f...
def my_atoi(string: str) -> int: int_max = 2**31 - 1 int_min = -2**31 new_str = '' stripped = string.lstrip() for char in stripped: if char in ['+', '-'] or char.isdigit(): new_str += char elif char.isalpha() or char == ' ': return int(new_str) return i...
from typing import List class ListNode: def __init__(self, x): self.val = x self.next = None def get_values(l1: ListNode) -> List[int]: l1_vals = [] while l1.next is not None: l1_vals.append(l1.val) l1 = l1.next if l1.val: l1_vals.append(l1.val) return l1_...
from typing import List def binary_search(arr: List[int], target: int) -> int: """Returns index of target value if found otherwise -1""" left = 0 right = len(arr) - 1 while left <= right: pivot = left + (right - left) // 2 if arr[pivot] == target: return pivot i...
def longest_substring(string: str) -> int: chars = set() max_len = 0 for index in range(len(string)): if string[index] not in chars: chars.add(string[index]) else: chars = set() chars.add(string[index]) max_len = max(len(chars), max_len) retur...
# -100.0 < x < 100.0 # n is a 32-bit signed integer, within the range [−231, 231 − 1] def pow(x: float, n: int) -> float: if n > 0: return 1/x if n == 1: return x return x * pow(x, n - 1) if __name__ == '__main__': x = 10 n = 2 result = pow(2.0000, 10) print(f'result ->...
## Number 1 phonebook_dict = { 'Alice': '703-493-1834', 'Bob': '857-384-1234', 'Elizabeth': '484-584-2923' } elizabeth_1 = phonebook_dict['Elizabeth'] print('Elizabeths Number: ' + elizabeth_1) phonebook_dict['Kareem'] = '938-489-1234' del phonebook_dict['Alice'] phonebook_dict['Bob'] = '968-345-2345' p...
# Lecture Example 1 from turtle import * forward(100) right(90) forward(100) right(90) forward(100) right(90) forward(100) mainloop() # Lecture Example 2 from turtle import * up() forward(50) left(90) forward(50) left(90) down() forward(100) left(90) forward(100) left(90) forward(100) left(90) forward(100) mainlo...
#!/usr/bin/env python # In this simple RPG game, the hero fights the goblin. He has the options to: # 1. fight goblin # 2. do nothing - in which case the goblin will attack him anyway # 3. flee class Hero: def __init__(self, hero_health , hero_power): self.power = hero_power self.health = hero_he...
# Sample 1.3: Polynomial Regression over y=x^3+2x^2+3 import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.pipeline import make_pipeline X = [x for x in range(20)] X = np.a...
# Sample 1.5: Diabetes Linear Regression import numpy as np import matplotlib.pyplot as plt from sklearn import datasets, linear_model from sklearn.metrics import mean_squared_error diabetes = datasets.load_diabetes() X = diabetes.data[:, np.newaxis, 2] X_train = X[:-20] X_test = X[-20:] y_train = diabetes.target[:-...
# This work is much pimped from this example of scikit-learn's documentation: # http://scikit-learn.org/stable/auto_examples/neural_networks/plot_rbm_logistic_classification.html """ ============================================================================== Restricted Boltzmann Machine features for digit cl...
class node: def __init__(self,data): self.data = data self.left = None self.right = None def bst(root, num): if root is None: return False elif root.data == num: return True elif num < root.data: return bst(root.left, num) elif num > ro...
n = int(input()) st = input() st_length = int(len(st)) temp = [] temp_length = len(temp) st2 = "" for i in range(int(st_length)-1, int(st_length/2)-1, -1): temp.append(st[i]) st2 = st2.join(temp) m = len(st2) for j in range(int(m)): if st2[j] == ']': st2 = '[' elif st2[j] == ')': ...
from sorter import Sorter import time ''' Time Complexity: O(n^2) Space Complexity: O(1) Divide into sorted and unsorted parts Iterate over unsorted segment, insert the element viewed into correct position of sorted list Comparing unsorted to sorted elem 'x'. Move unsorted elem to correct position then first...
import string def compare_elements(list1, list2): found = True shift = 0 if list1: for i, el in enumerate(list1): if el != list2[i]: found = False shift = i + 1 return found, shift def search_in_text(p: string, t: string): start_index = 1 t...
import numpy as np from typing import Tuple class DataPool(object): """ DataPool is used to store all datas, including annotated and unannotated data. DataPool also provide a unified data acquisition interface. """ def __init__(self, annotated_texts: list, annotated_labels: list, ...
import time import sys import sound def main(): print(' ') print(' ') print('Instructions: Input drinking schedule.') print(' ') c = ':' hourz = input('Hours: ') minz = input('Minutes: ') secz = input('Seconds: ') while True: print(' ') hour = int(hourz) ...
# -*- coding: utf-8 -*- """ Created on Sat Mar 3 09:59:38 2018 @author: mpkra """ list1 = [3, 4, -1, 5, -4] list2 = [3, 4, -8, 15, -1, 2] def max_contig_sum(L): """ L, a list of integers, at least one positive Returns the maximum sum of a contiguous subsequence in L """ lists = [] def i...
"""Drawing forests in a loop.""" __author__ = "730224009" # The string constant for the pine tree emoji TREE: str = '\U0001F332' given_depth: int = int(input("Depth: ")) counter: int = 1 while given_depth > 0: print(TREE * counter) counter = counter + 1 given_depth = given_depth - 1
"""Unit tests for dictionary functions.""" # TODO: Uncomment the below line when ready to write unit tests from exercises.ex06.dictionaries import invert, favorite_color, count __author__ = "730224009" def test_invert_short() -> None: """Ensures invert returns inversion of short given dict.""" assert invert...
# a = "abcdedj" # year = input("请输入输入") # print(a[int(year)%12]) a = "鼠牛虎兔龙蛇马羊猴鸡狗猪" # for year in range(2000,2019): # # print(' %s 年 生肖 %s a' %{year,int(year)%12}) # print(' 年 %s 生肖 %s' %(year, a[int(year)%12])) # # print(' %s 年 生肖 %s a' %{year,a[year%12]}) # num = 5 # while True: # if num > 10: #...
# def current_beat(): # max = 100 # nums = (1, 2, 3, 4) # i = 0 # result = [] # while len(result) < max: # if i >= len(nums): # i = 0 # result.append(nums[i]) # i += 1 # return result # def current_beat(): # nums = (1, 2, 3, 4) # i = 0 # while Tr...
""" Generators - Generators are iterators -generators can be created with generator functions -generator functions use the yield keyword -generators can be created with generator expressions Generator functions: -generator functions are similar to normal functions but use the yield keyword instead of return - can ...
tuple1 = ('colt', 'blue', 'rust', 'matt') # this method counts how many times the item being passed in exists tuple1.count(1) print(tuple1.index("blue")) # will tell us what the index is of the value
animal = input(" what is your favorite animal?") if animal: # a non-empty string is truthy, while an empty string is falsey print(animal + ' is my favorite too!') else: print("You didnt say anthing!") """ We can call values that will resolve to True as "truthy" , or values that will resolve to False as "fals...
def eat(food, is_healthy): ending = "because YOLO!" if is_healthy: ending = "because my body is a temple" return f"I'm eating {food}, {ending}" def nap(num_hours): if num_hours >= 2: return f"Ugh I overslept. I didn't mean to nap that long!" return f"I'm feeling refreshed after my ...
""" Class Methods *not used very much at all -Class methods are nethods (with the @classmethod decorator) that are not concerned with instances, but the class itself. """ """ Class Attributes -we can also define attributes directly on a class that are shared by all instances of a class and the class itself. - cla...
# creating a dictionary method 1 cat = { "name": "arthur", "age": 2.5, "isUgly": True } print(cat) # creating a dictionary method 1 cat2 = dict(name="arthur", age=2, isugly=True) # here the first value does not have to be declared a string, once # commutated it will become one automatically print(cat2)
instructor = { "name": "saul", "owns_dog": True, "age": 26, "favorite_language": "JavaScript", "is great": True } for v in instructor.values(): # iterates for value print(v) for k in instructor.keys(): # iterates for key print(k) for i in instructor.items(): # iterates for key and valu...
nums = [1, 2, 3, 4, 5, 6, 7] odd_nums = [num for num in nums if num % 2 != 0] print(odd_nums) students = ["austin", "racheal", "maria", "saul", "ayden"] teachers = ["blerk", "matt", "saul", "maria"] names = [name.upper() for name in students if name in teachers] print(names)
""" Filter - there is a lambda for each value in the iterable. -returns filter object which can be converted into other iterables -the object contains only the values that return true to the lambda """ l = [1, 2, 3, 4] evens = list(filter(lambda x: x % 2 == 0, l)) print(evens) names = ["austin", "amy", "arnold", "...
instructor = { "name": "saul", "owns_dog": True, "age": 26, "favorite_language": "JavaScript", "is great": True } # looking for a key # key in dictionary "name" in instructor # True "movie" in instructor # False if "name" in instructor: print("there is a name") # looking for a value if "s...
1, 1, 2, 3, 5, 8 def get_multiples(num=1, count=10): next_num = num while count > 0: yield next_num count -= 1 next_num += num
# abs ****************** # will find the absolute value of the an # int or a float # example abs(-5) # note, that the absolute value # of a negative number is a positive value # example above would be 5 # sum ******************* sum([1, 2, 3, 4], 10) """ can take two arguments, the second is not nesseary the firs...
#!/usr/bin/python -tt from math import sqrt def isprimenumber(n): if n == 2 or n == 3: return 1 d = 2 h = int(sqrt(n)) while d <= h: if not n % d: return 0 d += 1 return 1 if __name__ == "__main__": n = 2 c = 1 while c != 10001 + 1: if isprimenumber(n): print n, c ...
klist=[2,5,6,1,2,8,33,77,12] #print(klist.sort()) temp=0 for i in range (len(klist)): for j in range (len(klist)): if klist[i]>klist[j]: continue elif klist[i]<klist[j]: temp=klist[j] klist[j]=klist[i] klist[i]=temp #빈 공간인 temp에 klist[j]를 넣고 #klist[j]에는 [i]를 넣고 #[i]에 temp를 넣으면...
print("랜덤으로 숫자 불러오기 \n") import random for i in range(0,5): print("%f"%random.random(),end=' ') print("\n","="*50,"\n") for i in range(0,5): print("%d"%random.randint(1,3),end=' ') print("\n","="*50,"\n") for i in range(0,5): print("%d"%random.randint(1,45),end=' ') print("\n","="*50,"\n")
# coding: utf-8 # In[124]: datalist=[28,31,24,25,30,32,20,30,31,26,31] print(datalist) print("데이터의 총 개수는 : ",len(datalist)) # In[159]: def mMean(): ave=sum(datalist)/len(datalist) print("데이터의 평균값은 : ",ave) return ave def mMedian(): #data sort datalist.sort() if len(datalist) % 2 ==1: ...
a=3 b=3 print("a is b:",a is b) print("a == b:",a == b) print(id(a)) print(id(b))
# coding: utf-8 # In[1]: import pandas as pd scientists = pd.DataFrame(data={'Occupation':['Chemist','Statistician'], 'Born':['1920-07-25','1846-06-13'],'Died':['1958-04-16','1937-10-16'], 'Age':[37,61]},index=['Rosaline Franklin','William Gosset'], columns=['Occupation','Born','...
fruit=['apple','melon','grape','strawberry'] r=[] a=0 while True: n=int(input("10이상의 수를 입력하세요: ")) if 0 <n <10 : print("10이상의 수를 입력하세요:") elif n>=10: for x in range(1,n+1): r.append(a) if len(r)%3==0: print("%d. "%x+'[apple]') if len(r)%4==0: print("%d. "%x+'[melon]') ...
# coding: utf-8 # In[40]: datalist=[28,31,24,25,30,32,20,30,30,31,26,31] print(datalist) print("데이터의 총 개수는 : ",len(datalist)) # In[62]: def mMean(): print("데이터의 평균값은 : ",sum(datalist)/len(datalist)) def mMedian(): #data sort datalist.sort() if len(datalist) % 2 ==1: print("데이터의 중앙값은 : ",...
#import from Python-libraries import math """ Author: Amanda Klingner Filename: PositionsOfLine.py Description: Class for save the postions of the virtuell line(beginn (x,y) and end(x,y)) to drive in which course """ class PositionsOfLine: # global variables for Postion 1 (x,y) and for the Position 2 (x,y) global xPo...
'''The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.''' Sum = 0 for i in range (1,1000): Sum += i**i #print (i,Sum) print (str(Sum)[-10:])
"""2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000?""" power = 1000 base = 2 result = str(base**power) print(result) print(type(result)) sum = 0 for letter in result: sum += int(letter) print (sum)
import datetime import random def bubbleSort(array): for i in range(0,len(array)): for j in range(0,len(array)-1-i): if array[j+1] < array[j]: temp = array[j+1] array[j+1] = array[j] array[j] = temp def populateList(numElements): testList = [] for i in range(0,numElements): testList.append(int(...
import pandas as pd import matplotlib.pyplot as plt import numpy as np import pickle from sklearn.model_selection import cross_val_score from sklearn.linear_model import Lars from sklearn import svm def build_df(): print("Lendo dados") df = pd.read_csv("https://raw.githubusercontent.com/owid/covid-19-data/mas...
# -*- coding:utf-8 -*- """User representation.""" class User(object): """Object representation of user.""" def __init__(self, name: str, age: int): """ Construct a new user. Args: name: user's name age: user's age """ self.name = name ...
from datetime import datetime, timedelta from dateutil import parser def past_time(old_date):  # Convert from a string into a datetime field  old_date = parser.parse(old_date)  # Find the difference in time between now and the old date  date_difference = datetime.now() - old_date  # Split the time difference in...
name = input("Kirjoita A tai B: ") if name == "A": print ('Hei ' + name) elif name == "B": print ('Poo ' + name) else: print ('jotain')
def partition(ar,start,end): piv = ar[end] swap_pos = start for i in range(start,end): if ar[i] < piv: ar[i],ar[swap_pos] = ar[swap_pos],ar[i] swap_pos += 1 ar[end],ar[swap_pos] = ar[swap_pos],ar[end] return swap_pos def find_median(ar,start,end,mid): piv_idx ...
import abc class Fitness(abc.ABC): """ An abstract class for fitness evaluation. Defines the size of the individual (num_features). Calculates the fitness for an individual through the evaluate_task method. The game_name method is used for logging. """ @abc.abstractmethod def game_name(...
#Single line comment in python ''' A multiline comment here ''' #Multiline comment #can also be written this way ''' radius = int(input("Enter the radius of a circle \n")) area_of_a_circle = 3.1415 * radius * radius circumference_of_a_circle = 2 * 3.1415 * radius print(f"Area = {area_of_a_circle} and Circumference = ...