text stringlengths 37 1.41M |
|---|
# https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/description/
# 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)... |
# https://leetcode.com/problems/path-sum-iii/description/
# 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 pathSum(self, root, T):
"""
:type root: Tr... |
# https://leetcode.com/problems/convert-a-number-to-hexadecimal/description/
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0: return '0'
if num < 0: num &= ((1 << 32) - 1)
hex = {n:str(n) for n in xrange(10)}
... |
# anagram = both strings must contain the same exact letters in the same exact frequency
# --> the length of both strings must be equal
# we'll have two strings --> both can be any length, and can be different
# to make into anagram, we have to remove characters from the longer string
#
# how will we know which ... |
# https://leetcode.com/problems/find-largest-value-in-each-tree-row/description/
# 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 largestValues(self, root):
... |
# Implement binary search given an integer array
# Given integer array, integer to find --> output whether integer is inside the array
# Array --> not guaranteed to be sorted
# [1, 2, 3], 4
def binarySearch(array, integer):
# WE can asssume the array is sorted
if not array:
return False
left = 0
right = len(a... |
# https://leetcode.com/problems/add-two-numbers/description/
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, L1, L2):
"""
:type l1: ListNode
:type l... |
# https://leetcode.com/problems/find-right-interval/description/
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def findRightInterval(self, intervals):
"""
:type intervals: List[Int... |
a = int(input("Donnez un entier : "))
for i in range(1, a+1):
if a % i == 0:
print(i) |
# a = 1
# b = 2
# print("a =", a, "et b = ", b)
# a, b = b, a
# print("a =", a, "et b = ", b)
#
# # methode 2
# a = 1
# b = 2
# print("a =", a, "et b = ", b)
# ainit = a
# a = b
# b = ainit
# print("a =", a, "et b = ", b)
# TD 2 EX 1
# TD 2 EX 3
|
def creditAAoAIncreaseStrategy( annualApplicationCount, initialCreditWait, numberOfYears ):
int_format_str = '{:2d}';
float_format_str = '{:8.4f}';
i = 1.0;
step = 1.0 / float(annualApplicationCount);
temp = float(initialCreditWait);
while ( i < annualApplicationCount * numberOfYears ):
newTemp = ( temp ... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import os
import csv
# In[6]:
#open the csv path
csvpath = os.path.join('budget_data.csv')
#import the csv
with open(csvpath) as csvfile:
csvreader=csv.reader(csvfile,delimiter=',')
months=0
revenue=0
rows=[r for r in csvreader]
c... |
"""
GeneticAlorithm operates over populations of chromosomes
Properties:
population_size: # chromosomes in populations
genotype: structure of each chromosome
generations: list of successive populations
Methods:
fit: runs the genetic algorithm, using selection, crossover, an... |
'''
May 2017
@author: Burkhard
'''
# Spaghetti Code #############################
def PRINTME(me):print(me)
import tkinter
x=y=z=1
PRINTME(z)
from tkinter import *
scrolW=30;scrolH=6
win=tkinter.Tk()
if x:chVarUn=tkinter.IntVar()
from tkinter import ttk
WE='WE'
import tkinter.scrolledtext
outputFrame=tkinter.ttk.Lab... |
'''
May 2017
@author: Burkhard A. Meier
'''
#======================
# imports
#======================
import tkinter as tk
from tkinter import ttk
# Create instance
win = tk.Tk()
# Add a title
win.title("Python GUI")
# Adding a Label
ttk.Label(win, text="A Label").grid(column=0, row=0)
#===============... |
'''
May 2017
@author: Burkhard A. Meier
'''
#======================
# imports
#======================
import tkinter as tk
from tkinter import ttk
# Create instance
win = tk.Tk()
# Add a title
win.title("Python GUI")
tabControl = ttk.Notebook(win) # Create Tab Control
tab1 = ttk.Frame(tabControl)... |
'''
May 2017
@author: Burkhard
'''
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
#--------------------------------------------------------------
fig = Figure(figsize=(12, 5), facecolor='white')
#----------------------------------... |
# -*- coding:utf-8 -*-
"""
剑指offer第29题
问题:数组中有一个数字出现次数超过数组长度的一半,请找出这个数字
思路:这个数出现的次数肯定比其它数出现的次数加起来还多,
当遇到相同的数时,count+=1,当遇到不同的数时,count-=1,当count==0时,表示前面出现次数最多
的数的次数少于等于其它数出现次数的总和,那么后面的数组中,显然有出现最多的数的次数比后面中其它出现次数的总和
还有多,重置当前数,count重新+/-1即可
网友提供:
采用阵地攻守的思想:
第一个数字作为第一个士兵,守阵地;count = 1;
遇到相同元素,count++;
遇到不相同元素,即为敌人,同归于尽,cou... |
#-*- coding:utf-8 -*-
"""
剑指offer第7题
问题:使用两个栈实现队列,appendTail在队列尾插入节点,pop删除头结点
思路:使用两个栈
"""
class Stack:
def __init__(self, maxsize):
self.maxsize = maxsize
self.arr = [0]*self.maxsize
self.top = 0
def isEmpty(self):
return self.top == 0
def getSize(self):
retur... |
# -*- coding:utf-8 -*-
"""
剑指offer第27题
问题:输入一颗二叉搜索树,将该树转换成一个排序的双向链表。要求不能创建任何新的结点,
只能调整树中结点指针的指向
思路:递归,先完成左子树,使得左子树中的每个结点的右指针指向比它大的数,左指针指向比它小的数,
并获得左子树的最大结点即双向链表往右走的最后一个节点,在递归完成右子树,
最后可以得到整个双向链表往右走的最后一个结点
"""
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right... |
# -*- coding:utf-8 -*-
"""
剑指offer第12题
问题:输入数字n,按顺序打印1到最大的n位进制数
思路:n太大时,暴力法不好,可以考虑求n位数的全排列,然后把前面的0不打印
全排列递归思路:首先固定最高位,然后全列剩下的——固定当前最高位,当位数超过n时,即排列好了一个数,再打印
"""
def print_to_max(n):
if n <= 0:
return
arr = [0]*n
print_arr(arr, 0)
def print_arr(arr, n):
for i in range(10):
# 先固定第n位,这里最高位... |
# -*- coding:utf-8 -*-
"""
剑指offer第13题
问题:在给定单向链表的头指针和一个结点指针,要求在O(1)时间内删除该结点
思路:由于是单向,如果查找到该结点的前一个节点,那时间复杂度是O(n),可以将该结点的
下个结点的数据复制给该节点,然后删除下一个结点
例如:1->2->3->4,删除3
1->3->3->4
1->3->4
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
def delete_node(head, node):
if nod... |
# -*- coding:utf-8 -*-
"""
剑指offer第21题
问题:定义栈的数据结构,实现一个能够得到栈的最小元素的min函
调用min,push,pop时间复杂度都是O(1)
思路:直接用两个栈,一个存储元素,一个存储当前最小值,
比如 4 5 2 3 6 1
元素栈4 5 2 3 6 1
最小栈4 4 2 2 2 1
当pop时,两个栈同时pop,元素栈top永远是压入的元素,最小栈top永远是当前最小值
"""
class Stack:
def __init__(self, max_size):
self.top = 0
self.max_size = max_size... |
import requests
import json
"""this function allows one to specify the exchange rate base
as a parameter and a json object specifying the foreign exchange rates is returned
"""
def get_base(n):
url = "http://api.fixer.io/latest?base="+n
r = requests.get(url)
return (r.json())
|
grade = int(input())
max = int(input())
if 0.9 * max <= grade <= max:
print("A")
elif 0.8 * max <= grade < 0.9 * max:
print("B")
elif 0.7 * max <= grade < 0.8 * max:
print("C")
elif 0.6 * max <= grade < 0.7 * max:
print("D")
else:
print("F") |
import logging
from random import randint
from time import sleep
from turtle import Turtle, Screen
logging.basicConfig(level = logging.DEBUG)
players = \
[
{ 'name': 'Ronny', 'color': 'red' },
{ 'name': 'Ginny', 'color': 'green' },
{ 'name': 'Bevin', 'color': 'blue' },
{ 'name': 'C... |
# -*- coding: utf-8 -*-
"""
@author: timpr
"""
class Player(object):
"""
An NBA player object, associated with a particular fantasy league in a particular week
"""
def __init__(self, player_name, player_id, nba_team, team_id, player_key,
stat_dict, is_injured):
"""
... |
# program Grading Nilai
nama = str(input("Masukan Nama: "))
nilai = int(input("Masukan Nilai: "))
hasil = None
if(nilai >= 85 and nilai <=100):
hasil = 'A'
print("Hallo",nama,"! Nilai anda setelah dikonversi adalah",hasil)
elif(nilai >= 80 and nilai <=84):
hasil = 'A-'
print("Hallo",nama,"! Nilai anda ... |
def tachycardia(age, average_heart_rate):
"""
Uses age and average heart rate data to determine if the patient is
tachycardic
:param age: user age
:param average_heart_rate: the average heart rate
:returns is_tachycardic: indication if average heart rate is tachycardic
"""
if age > 15:... |
import turtle
# fruit = "apple"
# for idex in range(5):
# currentChar = fruit[idex]
# print(currentChar)
# fruit = "apple"
# for idx in range(len(fruit) - 1, 1, -1):
# print(fruit[idx])
# fruit = "dragons"
#
# position = 0
# while position < len(fruit):
# print(fruit[position])
# po... |
class Person:
def __init__(self, name, email, phone, friends=0):
self.name = name
self.email = email
self.phone = phone
self.friends = []
self.greeting_count = 0
def greet(self, other_person): #greet is method aka function. other_person is an argument
self.gree... |
# m1 = [
# [1,3],
# [2,4],
# ]
#
# m2 = [
# [5, 2],
# [1, 0],
# ]
#
# answer= []
# for i in range(0, len(m1)):
# row = m1[i]
# for j in range(0, len(row)):
# print(i, j)
# ans = m1[i][j] + m2[i][j]
# answer.append(ans)
#
#
# print(answer)
m1 = [
[1,3],
[2,4],
]
m2 = [
... |
#Ahmer Malik 9/16/2017
# Loop Exercises
# 1. 1 to 10
# Using a for loop and the range function, print out the numbers between 1 and 10 inclusive, one on a line. Example output:
# def sloop():
#
# for i in range(1,11):
# print (i)
#
# sloop()
... |
def convert_units(typ,constant,f,t):
"""Converts units
type should be one of them
'metric','time'
f and t should be one of them:
'pico','nano','micro','mili','centi','deci','base','deca','hecta','kilo','mega','giga','tera'
Attributes
----------
constant: int
constant numb... |
# -*- coding: UTF-8 -*-
from bs4 import BeautifulSoup
import re
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" clas... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 3 08:41:49 2019
@author: mukuljos
"""
#Strings
st = "10.10.101.21"
print(st.count("."))
#List
list_1 = ["1", "2", "3"]
list_1.append("4")
for i in list_1:
print (i)
even = [1,2,3,4,5]
odd = [7,8,9]
numbers = even+odd
#sort doesn't creat... |
print("\n\033[1;7;30m {:=^150} \033[m\n".format(" | MAIN MENU (2.0) | "))
from time import sleep
n1 = int(input('\033[1;30mEnter the 1th value:\033[m '))
n2 = int(input('\033[1;30mEnter the 2th value:\033[m '))
exit_program = False
while not exit_program:
sleep(0.5), print('\n\n\n\033[1;30m{}\033[m... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def make_rectangle(upper_left_point, lower_rect_point):
rect = {
'left_point': upper_left_point,
'right_point': lower_rect_point
}
return rect
def check_x_overlapping(left_rect, right_rect):
if left_rect['right_point'][0] >= ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def eval_prefix_expression(expression):
value = expression.pop(0)
if value in ["*", "+", "/"]:
op_1 = eval_prefix_expression(expression)
op_2 = eval_prefix_expression(expression)
if value == "*":
return op_1 * op_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def mth_element(line):
line.replace("\n", "")
tokens = line.split(" ")
index = tokens[-1]
tokens = tokens[:len(tokens)-1]
if int(index) > len(tokens):
return
print tokens[len(tokens) - int(index)]
if __name__ == '__main__':
... |
def computeArea(a, b, h):
A = (1/2)*(a+b)*h
return A
def main():
# receive values.
upperSide = float(input('Enter the upper side:'))
bottomSide = float(input('Enter the bottom side:'))
height = float(input('Enter the height of Trapezoid:'))
# Call the function.
area = computeArea(upper... |
import random
number = random.randint(1, 20)
def rand_call(guess ):
#global number
if guess < number:
print("Your guess number is low")
elif guess > number:
print("Your guess number is high")
def main():
guesses_no = 1
print("Type a number betwen 1 and 20: ")
while guesses_n... |
def main():
sentence = str(input('Please Enter a Sentence so I can fix it: '))
cleanedSentence = ''
for char in sentence:
char = char.lower()
if char.isnumeric():
char = ','
cleanedSentence = cleanedSentence + char
words_list = cleanedSentence.split(',... |
# Write your code here...
S = input()
lst = S.split(' ')
maxword = ''
minword = lst[0]
for word in lst:
if len(word) > len (maxword):
maxword = word
if len(word) < len ( minword):
minword = word
print( maxword)
print( minword) |
# Write a Python program that will accept the base and height of a
# triangle and compute the area.
# (Format the output -> 2 decimal places)
base = float(input("Enter the base of triangle: "))
height = float(input("Enter the height of triangle: "))
area = (base * height)/2
print("the Area is: ", format(area, '.2f')... |
pwd = int(input("Enter the password : "))
count = 1
while pwd!=128:
if(count <5):
print("wrong!, tray again")
count = count + 1
pwd = int(input("Enter the password : "))
else:
print("You exceeded the number of allowed attempts! ")
break
if pwd ==128:
print("True pass... |
def Factorial(n):
fact = 1
if n < 0:
fact = 'Error'
elif n == 0:
fact = 1
else:
x = n
while x > 0:
fact = fact * x
x -=1
return fact
def main():
number = int(input('Enter positive number:'))
print('Factorial (', number, ') = ', Fact... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import sys
import re
import nltk
fh = open(sys.argv[1], 'r')
rawtext = fh.read()
# based on several papers analysing the differences of male and female writers
# in English, we try to apply those rules to German - the quick and dirty way.... |
'''
Comparing single layer MLP with deep MLP (using TensorFlow)
'''
import numpy as np
import pickle
import scipy
from scipy.optimize import minimize
from scipy.io import loadmat
from math import sqrt
import time
import matplotlib.pyplot as plt
# Do not change this
def initializeWeights(n_in,n_out):
"""
# init... |
def generate_key(n):
letters = 'ABCDEFGHIJKLMNOPQRXTUVWXYZ'
key = {}
count = 0
# for each character in letters
for char in letters:
# assign char keys to key dict, assign the remainder of the count + the num n,
# divided by the length of the letters (25)
# this staggers all the letters by n without allowing... |
def readInput(seperator):
inPath = input('Please enter the path to the input file\n')
input_raw = open(inPath).read()
# obsolete end of lines
noObseol = 0
for c in input_raw[::-1]:
if(c == '\n'):
noObseol+=1
else:
break
if noObseol != 0:
input_clea... |
a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
print("Addition = {}".format(a+b))
print("Subtraction = {}".format(a-b))
print("Multiplication = {}".format(a*b))
print("Floor Division = {}".format(a//b))
print("Decimal Division = {}".format(a/b))
print("Remainder = {}".format(a%b))
print("Power = {}... |
input_str="hello world happy birthday"
input_list=input_str.split()
print(input_list)
print(input_list[::-1])
|
currentYear= 2021
birthYear=int(input("Enter ypu birth year "))
age=currentYear- birthYear
print("Your age is ",age," years")
|
import re
def min_length_validation(value, length):
return len(value) >= length
def max_length_validation(value, length):
return len(value) <= length
def is_digit_validation(value):
return value.is_digit()
def contains_digit_validation(value):
pattern = r'\d'
if re.findall(pattern, value):
... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def clear_false_index(*data_frames):
"""Clears the false indexing created by Pandas when saved as a CSV.
WARNING: ONLY USE ONCE PER DATA FRAME.
:param data_frames: Data Frames
:return: None
"""
for df in data_frames:
... |
#! /usr/bin/python3
import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""A class to control bullets fired from the ship"""
def __init__(self, ai_settings, screen, ship):
""" Create a bullet at the ship's current place"""
super().__init__()
self.screen = screen
# createa bullet rect at (0... |
'''
Can you create a program to solve a word jumble? (More info here.)
The program should accept a string as input, and then return a list of words
that can be created using the submitted letters. For example, on the input
"dog", the program should return a set of words including "god", "do", and "go".
Please impleme... |
# a = 12
# b = -a
# print(b) # -12
#
# c = a // b
# print(c)
#
# a += 2
# print(a)
#
# x = 1
# y = 2
# x += 2
# x = x + y
# y = x + y
# y = x + y
# print(y)
# operatory porównania
print("3" == 3) # false
print(3 > 3) # false
print(4 != 5) # true
print(4 >= 5) # false
print(3 <= 3) # true
print("Asia" < "Marta")... |
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def intersection(ll_a, ll_b):
ll_a_tail, ll_a_size = get_tail_and_size(ll_a)
ll_b_tail, ll_b_size = get_tail_and_size(ll_b)
# the tails of intersecting linked lists should be the same
if ll_a_tail is not ll_b_... |
def longest_subsequence(string, lst):
res = ''
for word in lst:
# print('{} is a subsequence of {} : {}'.format(word, string, is_subsequence(word, string)))
if is_subsequence(word, string) and len(word) > len(res):
res = word
return res
# tests if s1 is a subsequence of s2
def is_subsequence(s1,... |
def set_zero(matrix):
row_has_zero = False
col_has_zero = False
amt_of_rows = len(matrix)
amt_of_cols = len(matrix[0])
# check if first row has a zero
for col in range(amt_of_cols):
if matrix[0][col] == 0:
row_has_zero = True
break
# check if first column has a zero
for row in range(amt... |
def string_compression(string):
count = 1
res = []
i = 0
while i < len(string)-1:
if string[i] == string[i+1]:
count += 1
else:
res.append(string[i] + str(count))
count = 1
i += 1
if i > 0:
res.append(string[i] + str(count))
return min(string, ''.join(... |
def rotate_matrix(matrix):
length = len(matrix)
amt_of_layers = length // 2
for layer in range(amt_of_layers):
first, last = layer, length - layer - 1
for i in range(first, last):
# Select the 4 coordinates to be rotated by 90 degrees. The manner in which coordinates are selected is governed by the 'layer' ... |
# https://www.youtube.com/watch?v=ZRB7rIWO81U
# https://www.youtube.com/watch?v=7XmS8McW_1U
class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
current = self.root
for char in w... |
from stack import Stack
from sys import maxsize
class StackWithMin(Stack):
def __init__(self):
Stack.__init__(self)
self.min_stack = Stack()
def cur_min(self):
if self.min_stack.is_empty():
return maxsize
return self.min_stack.peek()
def pop(self):
value = super(StackWithMin, self).po... |
from collections import Counter
# Count char frequencies and return True if no more than one char freq is odd and False otherwise.
# A permutation may not have more than one type of char with odd freq.
def is_palindrome_permutation_1(a):
counter = Counter(a)
is_permutation = True
for count in counter.most_common... |
'''
This script showing you how to use a sliding window
'''
from itertools import islice
def sliding_window(a, n, step):
'''
a - sequence
n - width of the window
step - window step
'''
z = (islice(a, i, None, step) for i in range(n))
return zip(*z)
##Example
sliding_window(range(10), 2... |
import urllib2
'''
Script to download pdf from a url, you need specify the website URL, and change the
filename in the loop, it mostly useful to download a sequence of files with the
filename only differ by a sequence number, e.g. CH1.PDF, CH2.PDF, CH3.PDF ...
'''
def download_file(download_url, output_name):
''... |
print('Enter "x" for exit!!!')
print('Tests were all out of 100')
print('Enter marks obtained in 5 subjects')
m1 = input()
if m1 == 'x':
exit()
else:
m2 = input()
m3 = input()
m4 = input()
m5 = input()
mark1 = int(m1)
mark2 = int(m2)
mark3 = int(m3)
mark4 = int(m4)
mark5 = int(m5)
total = mark1 + mark2 + mar... |
# is_hot = False
# is_cold = False #True
# is_cool = True #False True
# is_hazy = False #True
# # 0 stands for
# if is_hot:
# print("Its hot today")
# print(
# else:
# print("Its a clumsy warm day take a chill")
# print("You can do whatever you want except for getting married!!!!!")"Please take an um... |
# names = ["Sankwa", "Lapha", "Gaxa", 1, 2, 8]
# # names [2] = "Pa Gaxa"
# for name in names:
# if name not in [1, 2, 8]:
# print(f'String: {name}')
# print("#####################################")
# else:
# print(f'Number: {name}')
# nums = [1, 20, 3, 5, 7]
# print(max(nums), " I... |
#from datetime import datetime, date, time
import datetime
#date and time -- today's date -- no time component
dan = datetime.date.today()
print (dan);
#dan = datetime.now()
#print (dan);
dan = datetime.time()
print (dan); #00:00:00
#hard-code a date
dan = datetime.datetime(2013, 6, 9, 11, 13, 3,... |
str1 = input("Enter a string: ")
print("Entered string is: ", str1)
print()
a = int(input("Enter the value of a: "))
b = int(input("Enter the value of b: "))
c = a + b
print("Value of c is: ", c)
print()
num1 = float(input("Enter num 1: "))
num2 = float(input("Enter num 2: "))
num3 = num1/num2
print("Value of num 3... |
import arithmetic
import unittest
# Testing add_numbers function from arithmetic.
class Test_addition(unittest.TestCase):
# Testing Integers
def test_add_numbers_int(self):
sum = arithmetic.add_numbers(50, 50)
self.assertEqual(sum, 100)
# Testing Floats
def test_add_numbers_float(self):
sum = arithmetic.add_... |
import sqlite3
con_obj = sqlite3.connect("test.db")
with con_obj:
cur_obj = con_obj.cursor()
cur_obj.execute("INSERT INTO books VALUES ('Pride and Prejudice', 'Jane Austen')")
cur_obj.execute("INSERT INTO books VALUES ('Harry Potter', 'J.K Rowling')")
cur_obj.execute("INSERT INTO books VALUES ('The Lord of the Ri... |
#!/usr/bin/python3
str1 = 'Hello Python!'
print("Original String: - ", str1)
print ("Updated String: - ", str1 [:6] + 'John')
|
# printing a simple string on the screen.
print("Hello Python")
# Accessing only a value.
a = 80
print(a)
# printing a string on screen as well as accessing a value.
a = 50
b = 30
c = a/b
print("The value of c is: ", c)
|
# Basic formatting
a = 10
b = 30
print("The values of a and b are %d %d" % (a, b))
c = a + b
print("The value of c is %d" % c)
str1 = 'John'
print("My name is %s" % str1)
x = 10.5
y = 33.5
z = x * y
print("The value of z is %f" % z)
print()
# aligning
name = 'Mary'
print("Normal: Hello, I am %s !!" % name)
print("Ri... |
#! /usr/bin/python
def main():
maxLength = 0
maxNumber = 0
for i in xrange(1000000):
print 'current number: ' + str(i)
length = getCollatzlen(i);
if (length > maxLength):
maxLength = length
maxNumber = i
print maxNumber;
def getCollatzlen(number):
count = 1
while number > 1:
if number % 2 == 1:
... |
class A:
def __init__(self):
print('In A init')
def feature1(self):
print('Feature1 is working')
def feature2(self):
print('Feature2-A is working')
class B(A):
def __init__(self):
super().__init__()
print('Init B printing')
def feature2(self):
prin... |
class Calculator:
@staticmethod
def sum(a=None, b=None, c=None):
if a!=None and b!=None and c!=None:
return a + b + c
elif a!=None and b!=None:
return a + b
else:
return a
print('Sum of 5 + 6 + 10:{}'.format(Calculator.sum(5, 6, 10)))
print('Sum of 6 + 7:{}... |
from numpy import array
from numpy import concatenate
arr1 = array([ 3, 4, 23, 12, 67])
arr2 = array([ 78, 23, 45, 25, 34])
arr1Copy = arr1
arr1[1] = 3
print('arr1:', arr1, " shallowCopy:", arr1Copy)
arr2DeepCopy = arr2.copy()
print('arr2:', arr2, " Deep Copy:", arr2DeepCopy)
arr2[0] = arr2[0] + 12
print('arr2:', ... |
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def compare(self, other):
if(self.name == other.name and self.age == other.age):
return True
else:
return False
harish = Person('Harish', 42)
radhika = Person('Radhika', 37)
... |
import pandas as pd
df = pd.DataFrame([[1,2,3],[4,5,6]],columns=["a", "b", "c"])
# 获取列名字
df.columns.values
# 读取文件
csv = pd.read_csv('../SalesJan2009.csv')
# 获取数据
csv.iloc[1,:]
csv.Transaction_date
# 添加列
csv["Price2"] = csv.Price
# 添加行
csv2 = csv.append(csv, ignore_index=True)
# 复杂查询
# select * from csv where Lati... |
"单分类的逻辑回归"
import tensorflow as tf
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('./dataset/credit-a.csv', header=None)
# 获取数据
x = data.iloc[:, 0:-1]
# 用replace方法替换-1
y = data.iloc[:, -1].replace(-1, 0)
# 定义模型
model = tf.keras.Sequential()
# 给模型里面添加层
model.add(tf.keras.layers.Dense(4, input... |
#1.write a python program to loop through a list of numbers and add +2 to every value to elements in list
list1=[1,2,3,4,5]
print("list1 is: ",list1)
for i in range(len(list1)):
list1[i]=list1[i]+2
print("After adding 2 to every elements in list1: ",list1)
print()
#2.write a program to get the below patte... |
print("Яке з введених чисел є найменшим ")
print("Число 1")
while True :
try:
n1=int(input())
break
except:
print("Please enter number")
print("Число 2")
while True :
try:
n2=int(input())
break
except:
print("Please enter number")
minimum... |
# MEMOIZATION:
# first of all, note that it is not momorization.
# memoization is an optimization technique used primarily to speed up computer programs
# by storing the result of expensive fucntion calls and returning the catched result
# when the same inputs occur again.
import time
def expensive_func(n):
prin... |
# IMMUTABLE:
# an immutable object is an object whose state cannot be modified after it is created.
# MUTABLE:
# this is in contrast of an immutable object, which can be modified after it is created.
a="shawki"
print(a)
# in python, a string is immutable.
# immutable doesn't mean that we can not assign it.
a="john"
pr... |
SIZES = ['small', 'medium', 'large']
STYLES = ['A', 'B']
class Tuxedo(object):
def __init__(self, style, size):
self.style = style
self.size = size
self.day = int()
def __str__(self):
return '%s%s' % (self.size, self.style)
def set_day(self, day):
self.day = ... |
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
pivot = pivot_binary_search(nums)
if pivot <= 0:
return target_binary_search(nums, 0, len(nums) - 1, target)
if target >= ... |
decision='Y' #to get inside the while loop the first time
productA=1000 -(1000 * 0.75)
productB=500 - (500 * 0.50)
productC=250 - (250 *0.25)
productD=100
productE=50
# varibles needed for the loops and the final invoice
quantA=0
quantB=0
quantC=0
quantD=0
quantE=0
priceA=0
priceB=0
priceC=0
priceD=0
pr... |
'''В диапазоне натуральных чисел от 2 до 99 определить,
сколько из них кратны каждому из чисел в диапазоне от 2 до 9.'''
multiple_numbers = [2, 99]
dividers = [i for i in range(2, 10)]
multiple_count = 0
for i in range(multiple_numbers[0], multiple_numbers[-1] + 1):
for j in dividers:
if i % j != 0:
... |
# First Variant
import sys
import random
def Count_memory(things):
summ = 0
for thing in things:
summ += sys.getsizeof(thing)
return summ
# FirstLesson
number = str(random.randint(100, 999))
summ = 0
prod = 1
for f in number:
summ += int(f)
prod *= int(f)
# SecondLesson
number = str(... |
# pygamede oyun animasyonlarını yapıp karakter hareketlerini kontrol edebileceğimiz önemli bir class var sprite
# bu hem kodumuzun daha temiz gözükmesi hem de karışmaması için böyle bir yol izleniyor.
import pygame
from random import randint, choice
pygame.init()
class Player(pygame.sprite.Sprite): # sprite.Sprite... |
import random
IMAGES = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
... |
def validarCadena(word):
word_list = list(word)
letters = list()
letters.append(word_list.pop(0))
for i in range(0,len(word_list)-1):
if(word_list[i]==letters[0]):
print(word_list[i]==letters[0])
word_list.pop(i)
else:
print (word_list)
... |
#Findest the greater number
list = [9,41,12,3,74,15]
maxNumber = list[0]
minNumber = list[0]
sum =0
avg =0
for num in list:
if num > maxNumber:
maxNumber = num
if num < minNumber:
minNumber = num
sum += sum+num
print('El mayor numero es:'+ str(maxNumber))
print('El menor... |
def factorial(n):
f = 1
for i in range (n,0,-1):
f = f*n
n= n-1
print(f)
num = input("enter your number")
factorial (int(num))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.