text
stringlengths
37
1.41M
class Trie: def __init__(self): self.root = {} def insert(self, word: str) -> None: root = self.root for ch in word: root.setdefault(ch, {}) root = root[ch] root.setdefault(None, 0) root[None] += 1 def countWordsEqualTo(self, word: str) -> i...
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def smallestFromLeaf(self, root: 'TreeNode') -> 'str': self.leaves = [] def dfs(root): if root.left: root.left.p = root ...
import math class Solution: def pathInZigZagTree(self, label: int) -> list: row = int(math.ceil(math.log2(label + 1))) ans = [] print(row) def f(n, row): if row == 1: ans.append(1) else: ans.append(n) next_n = ...
import functools class Solution: def checkPartitioning(self, s: str) -> bool: @functools.lru_cache(None) def ispalindrome(st, end): if st == end: return True elif st > end: return True elif s[st] != s[end]: return ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode: p=list1 for _ in range(a-1): p=p....
# coding=utf-8 ''' Created on 2017?8?20? @author: Administrator ''' from data_structure.Tree import list_to_tree # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def widthOfB...
class Solution: def sumOfThree(self, num: int) -> List[int]: if num==0: return [] if num%3==0: return [num//3-1,num//3,num//3+1] else: return []
# coding=utf-8 ''' Created on 2016?11?28? @author: Administrator ''' # Definition for singly-linked list with a random pointer. class RandomListNode(object): def __init__(self, x): self.label = x self.next = None self.random = None # hash table method # class Solution(object): # def...
# coding=utf-8 ''' Created on 2017?8?16? @author: Administrator ''' # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def largestBSTSubtree(self, root): """ :t...
# coding=utf-8 ''' Created on 2016?12?13? @author: Administrator ''' class ListNode(object): def __init__(self, x): self.val = x self.next = None def output(head): ans = [] p = head while p != None: ans.append(p.val) p = p.next return ans def list_to_list_node...
class Solution: def tictactoe(self, moves: list) -> str: def f(arrs): f = False for i in range(3): if all([x == "X" for x in arrs[i]]): return "A" if all([x == "O" for x in arrs[i]]): return "B" i...
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children if children is not None else [] """ class Solution: def diameter(self, root: 'Node') -> int: """ :type root: 'Node' :rtype: int """ ...
class Solution: def isRectangleOverlap(self, rec1, rec2): """ :type rec1: List[int] :type rec2: List[int] :rtype: bool """ x_overlap=max(0,min(rec2[2],rec1[2])-max(rec2[0],rec1[0])) y_overlap=max(0,min(rec2[3],rec1[3])-max(rec2[1],rec1[1])) return x_ov...
# Definition for Node. # class Node: # def __init__(self, val=0, left=None, right=None, random=None): # self.val = val # self.left = left # self.right = right # self.random = random class NodeCopy: def __init__(self, val=0, left=None, right=None, random=None): self.v...
# coding=utf-8 ''' Created on 2016?11?16? @author: Administrator ''' class Solution(object): def reconstructQueue(self, people): """ :type people: List[List[int]] :rtype: List[List[int]] """ max = -1 * float("inf") d = {} for i, j in people: d....
# coding=utf-8 ''' Created on 2017?9?3? @author: Administrator ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findSecondMinimumValue(self, root): ""...
# coding=utf-8 ''' Created on 2016?11?7? @author: Administrator ''' class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ from collections import Counter from itertools import cha...
# coding=utf-8 class Solution: def validTicTacToe(self, board): """ :type board: List[str] :rtype: bool """ import itertools nx=no=0 for ch in itertools.chain(*board): if ch=="X": nx+=1 if ch=="O": no+=1...
import math class Solution: def minimizeError(self, prices: list, target: int) -> str: arr = [] ce_sub_fe = [] sum_fe = 0 for price in prices: price = float(price) if math.floor(price) == price: target -= price else: ...
# coding=utf-8 ''' Created on 2016?10?26? @author: Administrator ''' class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] d = {"(":")", "[":"]", "{":"}"} for c in s: if c in d: stack.append(...
# Python program to find bridges in a given undirected graph # Complexity : O(V+E) from collections import defaultdict class Solution: def criticalConnections(self, n: int, connections: list) -> list: self.g = defaultdict(list) for u, v in connections: self.g[u].append(v) ...
import math class Solution: def visiblePoints(self, points: List[List[int]], angle: int, location: List[int]) -> int: points_angle = [] same_points = 0 x0, y0 = location for x1, y1 in points: if x1 == x0 and y1 == y0: same_points += 1 else: ...
# coding=utf-8 ''' Created on 2017?11?26? @author: Administrator ''' class Solution(object): def asteroidCollision(self, asteroids): """ :type asteroids: List[int] :rtype: List[int] """ i = 0 while i < len(asteroids) - 1: if asteroids[i] > 0 and astero...
# coding=utf-8 ''' Created on 2016?11?14? @author: Administrator ''' class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place...
# coding=utf-8 ''' Created on 13 Feb 2018 @author: Administrator ''' class Solution: def swimInWater(self, grid): """ :type grid: List[List[int]] :rtype: int """ import heapq visited = {(0, 0)} q = [(grid[0][0], 0, 0)] ans = 0 N = len(grid)...
from typing import List class Solution: def countLatticePoints(self, circles: List[List[int]]) -> int: ans=set() for x,y,r in circles: for x0 in range(x-r,x+r+1): for y0 in range(y-r,y+r+1): if (x0-x)**2+(y0-y)**2<=r**2: ans.add...
def tri(n): dp=[0]*(n+2) if n==0: return dp[0] elif n==1: dp[1]=1 return dp[1] else: dp[2]=1 for i in range(3,n+2): dp[i]=dp[i-1]+dp[i-2]+dp[i-3] return dp[n+1] n=int(input()) print(tri(n))
# Project Euler Problem 12: Highly divisible triangular number def solution(target): ans = 0 i = 1 while True: ans += i i += 1 if count_divisors(ans) > target: return ans def count_divisors(num): count = 1 factor = 2 while factor <= num: factor_power...
# Project Euler Problem 1: Multiples of 3 and 5 def solution(limit): ans = 0 for i in range(limit): if i % 3 == 0 or i % 5 == 0: ans += i return ans print(solution(1000))
#!/usr/bin/env python """ Emulate a spinning drum containing numbers from 1-47 and pick six numbers from it """ import os import sys import random from collections import deque import time def pre_spool(): """ Generate a 'pipe' (array) of numbers to put into a circular drum Accepts no arguments Retur...
''' Hi, here's your problem today. This problem was recently asked by Uber: Imagine you are building a compiler. Before running any code, the compiler must check that the parentheses in the program are balanced. Every opening bracket must have a corresponding closing bracket. We can approximate this using strings. ...
# Assigns a function to the whole menu def my_menu(): import os # clear statement os.system('cls') print(" ------------------------------------------------") print("| |") print("| 99FinalTest |") print("| Name...
from archivos import * #Aqui voy a generar el menu de la aplicación def menu(): print("Bienvenido a su agenda Usario:") print("-"*20) print("1. Agregar un registro") print("2. Mostrar registros") print("0. Salir") opcion = input() continuar = True if opcion == "1": agregarRegistr...
# Python program for implementation of MergeSort def mergeSort(arr): #write your code here # for dividing the array upto a point where only one element is left # then merge the elements based on order if len(arr) > 1: mid = len(arr)//2 # call mergesort on left part l...
def remove_duplicate(source_list): new_list = list({}.fromkeys(source_list).keys()) return new_list # 另一种方法 # new_list = [] # [new_list.append(i) for i in source_list if not i in new_list] # return new_list length = int(input("请输入列表的长度:")) my_list = [] for i in range(length): my_list.append(in...
def fn(n): sum = 0 if n == 1: return 12 else: return fn(n-1)*1.05 def sum(n): num = 0 for i in range(1, n+1): num += fn(i) return num print(sum(20))
# coding:utf-8 print('这是module1') my_book = '疯狂的Python讲义' def say_hi(user): print('%s , 你好,欢迎学习Python' %user) class User: def __init__(self,name): self.name = name def walk(self): print('%s 正在慢慢地走路' %self.name) def __repr__(self): return 'User[name = %s]' %self.name
''' Let's say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it. https://www.practicepython.org/exercise/2014/03/19/07-list-comprehensions....
''' Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even/odd number react differently when divided by 2? https://www.practicepython.org/exercise/2014/02/05/02-odd-or-even.html ''' numb = int(input('Number enter:...
# # LeetCode # Algorithm 118 Pascal's triangle # # Rick Lan, May 5, 2017. # See LICENSE # # Your runtime beats 66.75 % of python submissions. # class Solution(object): def nextRow(self, prev): """ :type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n)...
# # LeetCode # Algorithm 141 Linked List Cycle # # Rick Lan, May 6, 2017. # See LICENSE # # Your runtime beats 69.76 % of python submissions. # # # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def...
#!/usr/bin/env python from random import randint LEFT_BORDER = 1 RIGHT_BORDER = 20 TASK = 'Find the greatest common divisor of given numbers.' def get_gcd(first_number, second_number): while first_number != 0 and second_number != 0: if first_number > second_number: first_numb...
""" simple linear regression """ import math def linear_reg(d): """ regression based on a dataset """ #shorthands n = float(d.n()) sumX = d.sumX() sumY = d.sumY() sumXY = d.sumXY() sumXX = d.sumXX() sumYY = d.sumYY() #slope b = (n * sumXY - (sumX * sumY)) / ( n * sumXX- ...
def smaller(a, b): if a < b: return a else: return b def smallest(a, b, c): return smaller(a, smaller(b, c))
def whatIdo(M): """parameter : M – 변경할 리스트 return value : result – 변경된 리스트 새로운 리스트의 내용은 M의 원소를 규칙에 따라 변경하여 얻는다 """ # 함수를 완성하시오. l = len(M) ans = [] for i in range(l): li = [] for j in range(l): li.append(M[l - j - 1][i]) ans.append(li) return ans ...
weekdays = ["월", "화", "수", "목", "금", "토", "일"] month, day = input("날짜를 입력하시오(예:10/1) : ").split("/") # 10월 중 하루니까 day만 필요함 day = int(day) month = int(month) print("{}월 {}일은 {}요일이다".format(month, day, weekdays[(day % 7 + 2) % 7]))
from random import * print() print("Welcome to IncNumber Game") print() print("LET'S START") j = "Yes" i = 0 a = 0 while a <= 0: if j == "Yes" or j == "y" or j == "yes": while i <= 5: print("Game is on") p1 = int(input("Enter your number - ")) print() comp = str(p1+(randint(0,100...
# function input my_dict = { "Speros": "(555) 555-5555", "Michael": "(999) 999-9999", "Jay": "(777) 777-7777" } #function output [("Speros", "(555) 555-5555"), ("Michael", "(999) 999-9999"), ("Jay", "(777) 777-7777")] def tupleTups(): aList = [] tups = () for key, data in my_dict.items(): tup = () ...
names = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar"] animals = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas"] def nameOfPet(name, favorite_animal): combo = zip(name, favorite_animal) print combo print nameOfPet(names, animals)
sI = 45 mI = 100 bI = 455 eI = 0 spI = -23 sS = "Rubber baby buggy bumpers" mS = "Experience is simply the name we give our mistakes" bS = "Tell me and I forget. Teach me and I remember. Involve me and I learn." eS = "" aL = [1,7,4,21] mL = [3,5,7,34,3,2,113,65,8,89] lL = [4,34,22,68,9,13,3,5,7,9,2,12,45,923] eL = [] s...
""" Feb 26 2018 10.00 am Lecture 0101 """ class Tree: value: float def __init__(self): self.children = [] def __str__(self) -> str: pass def count_nodes(self) -> int: # if self.children == []: # BASE CASE # return 1 # else: # ...
""" Mar26 2018 """ class HastTable: def __init__(self): pass def __getitem__(self) def __setitem__(self, key: object, value: object) -> None: """ >>> ht = HashTable(2) >>> ht.capacity == 2 True >>> ht.__setitem__("one", 1) >>> ht["two"...
""" ## Binary Trees """ from typing import Union class BTNode: """ A Binary Tree, i.e. arity 2. """ def __init__(self, value, left: Union["BTNode", None]=None, right: Union["BTNode", None]=None) -> None: self.value, self.left, self.right = value, left, right ...
if __name__ == '__main__': grades = [NumericGradeEntry('csc148', '87', 1.0), NumericGradeEntry('mat137', '76', 2.0), LetterGradeEntry('his450', 'B+', 1.0)] for g in grades: # Use appropriate ??? methods or attributes of g in format print("Weight: {}, grade: {}, points: {}".format(g.weight, g.grade, g.convert_to_...
""" У вас есть примитивный калькулятор, который умеет выполнять всего три операции с текущим числом x: заменить x на 2x, 3x или x+1. По данному целому числу 1≤n≤10^5 определите минимальное число операций k, необходимое, чтобы получить n из 1. Выведите k и последовательность промежуточных чисел. Sample Input 1: 1 Sam...
""" Первая строка входа содержит число операций 1≤n≤10^5. Каждая из последующих n строк задают операцию одного из следующих двух типов: Insert x, где 0≤x≤10^9 — целое число; ExtractMax. Первая операция добавляет число x в очередь с приоритетами, вторая — извлекает максимальное число и выводит его. Sample Input: 6 In...
""" Purpose: ----------------------------------------------------------------------------------- - Use Regular Expression to sort out the titles in 'Name' ----------------------------------------------------------------------------------- """ import re def get_title(name): # Use a regular expression to search for ...
class BankAccount: # don't forget to add some default values for these parameters! def __init__(self, int_rate, balance): self.int_rate = int_rate self.balance = balance # your code here! (remember, this is where we specify the attributes for our class) # don't worry about user i...
def addSqurts(n): sum = 0 i = 1 while i <= n: sum += i**2 i += 1 return sum def squareSum(n): sum = 0 i = 1 while i <= n: sum += i i += 1 return sum**2 print squareSum(100)-addSqurts(100)
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ nodeA = he...
class TrieNode: def __init__(self, val): self.val = val self.word = False self.node = {} class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode('') def insert(self, word: str) -> ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: stacks = [list(), list()] current_stack = 0 next_s...
# E -> E + T # | T # T -> T * F # | F # F -> num tokens = [('1', 'num'), ('+','add'), ('2', 'num'),('*','puls'), ('5','num')] flag = 0 def parser_F(): global flag if tokens[flag][1] == 'num': v = int(tokens[flag][0]) flag = flag + 1 return v else: raise Exception("F") ...
class Solution(object): def verifyPreorder(self, preorder): """ :type preorder: List[int] :rtype: bool """ def build_bst(start, end, limit_min): if start == end: return True root = preorder[start] if root < limit_min: ...
from functools import lru_cache @lru_cache(10000) def match_simple(s, p): if not p and s: return False if not s and not p: return True s_index = 0 p_index = 0 p_ch = p[p_index] if p_ch == '*': p_index = p_index + 1 while p_index < len(p) and p[p_index] == '*': ...
from itertools import groupby from collections import defaultdict import re def make_groups(data): # sort data into groups delimited by new lines groups = [list(g) for k,g in groupby(data, lambda x: x=='')] groups = [g for g in groups if g != ['']] return groups def part1(data): # get sum of uniqu...
''' Objective: Design an experiment to calibrate the thermistor attached to your board. Hint: Use a (trusted) thermometer to collect ground truth. Questions to answer: 1. Which parameterized function is suitable for converting the raw value to a temperature? 2. What are the parameters for your setup? 3. If a single re...
from abc import ABC, abstractmethod class Startup(ABC): def Ideas(self): print("__________") class Infra(Startup): def Ideas(self): super().Ideas() print("INFRASTRUCTURE ON WORK AREA") print("1.Commnunication networks") print("2.Electric system") print("3.Cost inv...
import threading, time def print_time_(threadName, delay, counter):# passing var and printing while counter: time.sleep(delay) threadLock.acquire() print ("%s: %s" % (threadName, counter)) counter -= 1 threadLock.release() threadLock.release() threadLock.release() cl...
def multiplier_of(n): def multiplier(number): return number*n return multiplier multiplywith5 = multiplier_of(5) print(multiplywith5) print(multiplywith5(9))
word0032 = input("Enter the string : ") word0032.lower() word0032 = ''.join(sorted(word0032)) for char in word0032: print(word0032.count(char))
#! python3 """Program to detect password strength""" import re def strong_pass(Password): if re.match(r'([a-zA-Z0-9]).{8,}', Password) is not None: print ('Strong Password') else: print ('Weak Password') pwd = "abracadaRAA@321" strong_pass(pwd)
""" Minimax agent with alpha beta pruning """ import random from heuristics import * ILLEGAL_MOVE = -1_000_000_000 # arbitrarily low number to indicate illegal move def minimax(board, depth=3, verbose=False): """ minimax without ab pruning. can only seem to get depth 3 with this. """ if board.get_winner() ...
print('Hello, Djangogirls! lol') if 3<2: print('It works!') else: print('5 ist nicht größer als 2') name= 'Sonja' if name== 'Pia': print('Hey Pia!') elif name== 'Sonja': print('Hey Sonja!') else: print('Hey anonymous!') volume=57 if volume<20: print("Das ist etwas leise!") elif 20<= volume < 40: print("Das ist...
### python code based on getting started with python from kaggle site https://www.kaggle.com/c/titanic-gettingStarted/details/getting-started-with-python ### import relevant packages import csv as csv ## setup packages needed import numpy as np import os as os ### set working directory os.chdir('/Users/Teleak/Desktop...
from tkinter import * from tkinter import messagebox positions = [] buttons = [] for i in range(9): positions.append("-") buttons.append(Button) size = 100 board = Tk() board.title("TicTacToe") board.geometry("340x340") board["bg"] = "green" turn = ["x"] def check(): row_1 = positio...
# Advent of Code - Day 2 # https://adventofcode.com/2019/day/2 # Part 1 input = [1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,9,1,19,1,19,6,23,2,6,23,27,2,27,9,31,1,5,31,35,1,35,10,39,2,39,9,43,1,5,43,47,2,47,10,51,1,51,6,55,1,5,55,59,2,6,59,63,2,63,6,67,1,5,67,71,1,71,9,75,2,75,10,79,1,79,5,83,1,10,83,87,1,5,87,91,2,13,91,95,1...
ticker = "HAKA-USDT" def count_unique_pair(df): describe_df = df.describe() print(f"You traded {describe_df.iloc[1][0]} different trading pairs in the last seven days.") """ Counts the number of unique trading pairs which were traded by user in the last 7 days, up to 500 transactions """ def...
from numpy import * import numpy as np import matplotlib.pyplot as plt import pandas as pd from pandas import DataFrame as df def sum_of_errors(b,m,points): totalerror=0 for i in range(0,len(points)): x=points[i,0] y=points[i,1] totalerror+=((y-(m*x+b)))**2 return totale...
import tkinter as tk import random root = tk.Tk() root.title('猜数字游戏') tk.Label(root, text="请输入一个1——100之间的整数:").grid(row=0, column=0) entry1 = tk.Entry(root) entry1.grid(row=0, column=1, padx=10, pady=10) random_num = random.randint(1, 100) var_猜数字 = tk.StringVar() var_猜数字_text = tk.StringVar...
""" https://leetcode.com/problems/count-and-say/ The count-and-say sequence is a sequence of digit strings defined by the recursive formula: countAndSay(1) = "1" countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is then converted into a different digit string. To determine how yo...
def edit_distance(s1, s2): """ Finds the minimum number of edits to make s1 and s2 equal. Uses dynamic programming. """ # set up the cache # position (m, n) in the cache will contain the edit distance between # the string composed of the first m elements of s1 and the string composed ...
""" https://leetcode.com/problems/jump-game/ You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. """ class Solution: def...
""" https://leetcode.com/problems/implement-strstr/ Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Clarification: What should we return when needle is an empty string? This is a great question to ask during an interview. For the purpose ...
""" https://leetcode.com/problems/3sum-closest/ Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. """ def sum3(l, target): if len(l) < 3:...
from Fireworks import * print('Would you like to customize it? (yes or no)') f = input() if f == 'yes': number = int(input('Number of particles in a firework:(Default 5)\n')) cs = [] for i in range(5): cs.append(tuple([int(i) for i in input('Colors' + str(i) + ':(Default 2 of them are with single ...
#!/usr/bin/env python import sqlite3 as lite import sys import hashlib from itertools import product from string import * # The purpose of the script is to use multiple convinations of values to generate hashes and find one in the db # It is believed that cyrpto function was something like: CommonHash($salt,$pass) # ...
""" Creates randomly generated art using pre-defined functions """ import random from PIL import Image import math def build_random_function(min_depth, max_depth): """ Builds a random function of depth at least min_depth and depth at most max_depth (see assignment writeup for definition of depth ...
""" Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Things to note: Topological Sorting for a graph is not possible if the graph is not a DAG. Topological Sort orderings are not unique Topol...
def hanoi(n,source,spare,target): ''' Objective : To solve tower of hanoi Input Parameters : n = Number of disks source = The initial pole no. containing all the disks spare = The pole no. used for temporary storing the disks target = The pole no. where disks are to be transf...
# works for python 2 # modules to read data from urls import urllib import urllib2 import string import sys from bs4 import BeautifulSoup # make program look like a browser, user_agent user_agent = 'Mozilla/5 (Solaris 10) Gecko' headers = { 'User-Agent' : user_agent } # pass in the word into the search bar a.k.a crea...
friendNames = [] while True: print("Enter the name of friend " + str(len(friendNames) + 1) + " (Or enter nothing to stop.):") name = input() if name == '': break friendNames = friendNames + [name] # list concatenation print("Your friend's names are:") for name in friendNames: print(' ...
#Brian Condon # 28/02/18 Week 5 formatting exercise # prints the headings # opens the data file print("petal length, petal width, sepal length, sepal width") with open("data/iris.csv") as data_file: # loops through the data file # prints and formats the data using the line split for line in data_file: ...
# Brian Condon 06/02/18 # Collatz Conjecture without integer prompt n = 17 # Creating a while loop for when the n is equal to 17 while n == 17: # If the remainder is 0 means it is an even number if n % 2 == 0: # if even divide by 2 n = n / 2 print(n) # if the remainder is not 0 then the number is o...
# Dictirionaries purse = dict() purse['money'] = 12 purse['candy'] = 3 purse['tissues'] = 75 # whats in purse print(purse) # {'money': 12, 'candy': 3, 'tissues': 75} print(purse['candy']) purse['candy'] = purse['candy'] + 2 purse['candy'] += 2 print(purse) lst = list() lst.append(12) print("lst : " , lst) lst2 =...
c = {'a' : 10 , 'b': 1 , 'c' : 22} print(c) print(c.items()) print(c.values()) print(c.keys()) print(sorted( [ (value , key) for value,key in c.items()])) d = [ 1, 5 , 2, 3 , 0] d.sort() print(d) css = {'a' : 10 , 'b': 1 , 'c' : 22} print('\n------------------------------------\n') mytuple = list() mytuple2 = list(...
# coding=utf-8 # faktöriyel bulma faktoriyel = 1 while True: sayi = int(input("Sayı Giriniz : ")) for i in range(1 , sayi+1): faktoriyel *= i print (sayi ,". Faktöriyeli : ", faktoriyel) break # FONKSİYONLAR def merhaba(a): print("Merhaba Fonksiyonu Çalıştırıldı") print(a+2) merhab...
import sqlite3 import csv flist= [tuple(row) for row in csv.reader(open('static/data/out.csv', 'rU'))] connection = sqlite3.connect('database.db') with open('schema.sql') as f: connection.executescript(f.read()) cur = connection.cursor() print(flist) for x in flist[1:]: cur.execute("INSERT INTO houses (...
# -*- coding: utf-8 -*- """ Gradient Boosting ------------- A forecasting model using gradient boosting regression. It uses some of the target series' lags, as well as optionally some covariate series' lags in order to obtain a forecast. """ from typing import List, Optional, Tuple, Union from darts.logging import get...
s = 'hello world' mizans_contacts = {'anwar':'24663434','shah':'344321'} print(s[::-1]) placeholder = 'String234' print('Place my variable here: %s' %(placeholder)) print('Floating point number: %1.5f' %(15.145)) print('First variable {x} second: {y}'.format(x='mizan', y='hello')) print('Hel...