blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
ba7803e83f3047ea869d4bf6e19b9b2fb5531d0a | lovychen/NG_class_2014_Machine-Learning | /w_1_sgd/last.py | 3,670 | 3.671875 | 4 | # -*-coding:UTF-8-*-
# Created on 2015年10月20日
# @author: hanahimi
import numpy as np
import random
import matplotlib.pyplot as plt
def randData():
# # 生成曲线上各个点
# x = np.arange(-1, 1, 0.02)
# y = [2 * a + 3 for a in x] # 直线
# # y = [((a*a-1)*(a*a-1)*(a*a-1)+0.5)*np.sin(a*2) for a in x] # 曲线
#... |
7ad23ca35f1ad43993dd9e46dc74f6ee4c6d1d80 | sotsoguk/elementsOfPI | /ch11/11_7_minmax.py | 1,311 | 3.5625 | 4 | import random
def minmax(a):
# find the min and max simultanously
if not a:
return (-1,-1)
if len(a) == 1:
return a[0],a[0]
a_min = min(a[0],a[1])
a_max = max(a[0],a[1])
if len(a) == 2:
return a_min,a_max
upper_range_bound = len(a)-1
# if len(a) %2 :
# upp... |
2f532c4855c720cc19fcda5f54dc8a1b8703182a | sotsoguk/elementsOfPI | /ch04/multiplyxy.py | 534 | 3.921875 | 4 | def add(a,b):
k, t_a, t_b, carry_in, result = 1, a,b,0,0
while t_a or t_b:
ak, bk = a &k, b&k
carry_out = (ak & bk) | (ak & carry_in) | (bk & carry_in)
result |= ak ^ bk ^ carry_in
k, t_a, t_b, carry_in = k <<1, t_a >>1,t_b>>1,carry_out <<1
return result | carry_in
def ... |
d2408f38fee112832559542eed6d264e74045d75 | sotsoguk/elementsOfPI | /ch04/reverse_digits.py | 483 | 3.890625 | 4 | # Elements of Programming Interviews
# Chapter 04 - Primitives
# 4.8 Reverse digits
testCases = {123:321, 0:0, -8393:-3938}
def reverse_digits(x):
sign = -1 if x<0 else 1
x = abs(x)
result = 0
while x:
digit = x % 10
result *= 10
result += digit
x //= 10
return sign ... |
ab9657683a2491b56e18a1442d51347a8431a7d9 | sotsoguk/elementsOfPI | /ch11/11_3_cyclic_array.py | 628 | 3.84375 | 4 | # Chapter 11: Searching
# 11.3 Search smallest entry in cyclic sorted array
# eg [10,11,12,15,1,2,3,4,5]
def min_cyclic(a):
if not a:
return -1
left, right = 0, len(a)-1
while left < right:
mid = left + (right-left)//2
print(left,mid,right,a[left],a[mid],a[right])
# left en... |
52ba51f148ae61ec131a98eecc9e9af2307c860e | panthercoding/Summer_Lecture4 | /swift.py | 3,187 | 4.15625 | 4 | """
run pip install pandas in the Shell to download the Pandas module
"""
import pandas as pd
"""
Accepts a word token (string) and should remove
any non-alphabetic characters at the beginning and end of the word
Should return an empty string "" if there are no alphabetic characters
(try counting them using the cou... |
b2fdf9098842f75b7f2ab38cfdb77b652d3d0eb5 | balochCoder/pythoncourse | /PythonCourse/Coding/PythonBasicsI/lesson2.py | 472 | 4.03125 | 4 | # Data Types
# Fundamental Data Types
# int
# float
# bool
# str
# list
# tuple
# set
# dict
# Numbers (float takes lot of memory thank integer)
# int (numbers without decimal value) and float (numbers with decimal values)
# print(2+4)
# print(8-4)
# print(2*4)
# print(type(4/2)) type function show the type of variab... |
20bb243223d180691c620fd856409ade7577829f | balochCoder/pythoncourse | /PythonCourse/Coding/PythonBasicsII/functions.py | 136 | 3.578125 | 4 | def sum(num1,num2):
def another_sum(n1,n2):
return n1+n2
return another_sum(num1,num2)
total = sum(10,20)
print(total) |
49bf48fa135fa87993bd63cd1aff708e8106c2c1 | balochCoder/pythoncourse | /PythonCourse/Coding/PythonBasicsII/scoperules.py | 827 | 3.578125 | 4 | #1
# a = 1
# def confusion():
# a=5
# return a
# print(a)
# print(confusion())
#2
# a = 1
# def confusion():
# a=5
# return a
# print(confusion())
# print(a)
# #3
# a = 1
# def parent():
# a =10
# def confusion(): # not a in local scope but a have a value in parent scope
# retu... |
98a09ee22926902ad0e302188e774fff7ab0c65a | balochCoder/pythoncourse | /PythonCourse/Coding/PythonBasicsI/lesson4.py | 738 | 4 | 4 | # Variables
# Assigning Variables
# snake_case, Letters, Numbers, underscore, case sensitive
# iq = 80
# age = iq/4
#
# print(age)
# constant variables are written in upper case
# PI = 3.4
# print(PI)
#dunder variables
# __doc__ = 56
# Multiple variables
# a,b,c = 1,2,3
# print(a)
# Augmented Assignment Operator
... |
2a5d86f1942745b60ccbb8c0d9616186bd35618b | DmitryPolyan/learning-and-other | /some_pythons_practice/All_Balanced_Parentheses.py | 893 | 3.9375 | 4 | """
Write a function that makes a list of strings
representing all the ways you can balance n pairs of parentheses.
"""
import itertools
def get_variants(n: int) -> int:
"""
Ф-я перебора возможных вариантов расположения скобок
:param n: Кол-во пар скобок
"""
ways = 0
variants_list = list... |
6a3a9a4e190f041e464a5e44a6a1a7c9c557ffd6 | peircechow/cpy5p2 | /q06_kilograms_to_pounds.py | 110 | 3.609375 | 4 | print("Kilogram Pounds")
k=1
while k<11:
p=float(2.2*k)
print("{0:<9}{1:.1f}".format(k,p))
k+=1
|
39cfbb38da5d7e28186ad18dc63f9e29cfdc27a3 | jiangce/tglib | /parallelthread.py | 1,000 | 3.53125 | 4 | # -*- coding: utf-8 -*-
from threading import Thread
from math import ceil
class Pool(object):
def __init__(self, method, argsmap, threadcount):
self.method = self._wrapmethod(method)
self.argsmap = argsmap
self.threadcount = threadcount
def _wrapmethod(self, method):
def inn... |
50b03235f4a71169e37f3ae57654b7a37bcb9d10 | adamsjoe/keelePython | /Week 3/11_1.py | 246 | 4.125 | 4 | # Write a Python script to create and print a dictionary
# where the keys are numbers between 1 and 15 (both included) and the values are cube of keys.
# create dictonary
theDict = {}
for x in range(1, 16):
theDict[x] = x**3
print(theDict) |
86e3aa25fd4e4878ac12d7d839669eda99a6ea1c | adamsjoe/keelePython | /Week 1/ex3_4-scratchpad.py | 964 | 4.125 | 4 | def calc_wind_chill(temp, windSpeed):
# check error conditions first
# calc is only valid if temperature is less than 10 degrees
if (temp > 10):
print("ERROR: Ensure that temperature is less than or equal to 10 Celsius")
exit()
# cal is only valid if wind speed is above 4.8
if (windS... |
d3ab5cfe7bb1ff17169b2b600d21ac2d7fabbf70 | adamsjoe/keelePython | /Week 8 Assignment/scratchpad.py | 1,193 | 4.125 | 4 | while not menu_option:
menu_option = input("You must enter an option")
def inputType():
global menu_option
def typeCheck():
global menu_option
try:
float(menu_option) #First check for numeric. If this trips, program will move to except.
if float(menu_option).is_integer(... |
5933ede30987f68d290e8bf3a3ae9230188f5387 | adamsjoe/keelePython | /Week 8 Assignment/test.py | 1,467 | 3.5625 | 4 | class Member(object):
max_id = 0
def __init__(self, id_no, first_name, last_name, gender, email, card_no):
if id_no is None:
self._id_no = Member.max_id + 1
else:
self._id_no = int(id_no)
Member.max_id = int(id_no)
self._first_nam... |
7a9129051ac2465f7ea7af30f6960cd06e712e55 | adamsjoe/keelePython | /Week 8 Assignment/test2.py | 1,760 | 3.578125 | 4 | import csv
import json
import sys
BOOKLOANSFILE_CSV = 'bookloans.csv'
BOOKSFILE_CSV = 'books.csv'
MEMBERSFILE_CSV = 'members.csv'
BOOKLOANSFILE_JSON = 'bookloans.json'
BOOKSFILE_JSON = 'books.json'
MEMBERSFILE_JSON = 'members.json'
CURRENT_BOOKLOANSFILE_JSON = 'books_on_loan.json'
def create_json(file_in, file_out,... |
4720925e6b6d133cdfaf1fd6cf5358813bbec7e3 | george5015/procesos-agiles | /Tarea.py | 460 | 4.15625 | 4 | #!/usr/bin/python3
def fibonacci(limite) :
numeroA, numeroB = 0,1
if (limite <= 0) : print(numeroA)
elif (limite == 1) : print(numeroB)
else :
print(numeroA)
while numeroB < limite:
numeroA, numeroB = numeroB, numeroA + numeroB
print(numeroA)
return
numeroLimite = int(input("Ingrese el numero para cal... |
6abaff059e03ece9366ae7cd85ba171875935818 | Frederik-Kohl/B9122 | /B9122_HW_1_Question_4.py | 819 | 3.984375 | 4 | fh = open("question4.txt") # Open text file
txt = fh.read() # Read contents of text file and store in string
fh.close() # Close file
txt = txt.lower() # Convert all letters to lowercase
words = txt.split() # Obtain list of words from string, words may also be separated by \n. Hence don't specify sep
count_dict = d... |
5ead9bc20bf23f34b507557b54df327833150f5c | lalit-1729/Assignment-1 | /Ques9.py | 5,412 | 4.25 | 4 | #matrix multiplication using oop
from os import system # to clear the console window after every successful run
class Matrix:
def __init__(self, row, column):
self.row = row
self.column = column
def matrix_input(self):
#Initializing a rows x columns matrix with all elements equal to 0
... |
7f693ac5f2cd6518bdaf195ea40ffbc131d67836 | children702/test | /demo.py | 3,444 | 4.5 | 4 | '''
第一节
python的方法
1、print() 打印输出
2、input() 捕获输入值,将输入的值赋值给变量 使用input输入的数据格式都是字符串
a = input ("请输入数字")
b = input ("请输入数字")
print(a+b)
3、type() 数据的转换 #数据转换的规律:1、任何数据都可以转换成字符串 2、字符串类型转成其他格式,需要满足[长得像]这个条件 3、小数和整数可以互相转换
a = int (input("请输入数字:"))
b = int (input("请... |
16fa4a1f06b93369efa17691ba4071dac0284e7e | chibipaper/python_F-B | /testPyGame.py | 1,447 | 3.5625 | 4 | import pygame
def display_map():
W = int(2003*0.25)
H = int(2500*0.25)
introScreenImage = pygame.image.load("map.png")
introScreenImage = pygame.transform.smoothscale(introScreenImage, (W, H))
screen = pygame.display.set_mode((W+300,H))
screen.blit(introScreenImage, (300,0))
pygame.d... |
9d053facdac5fae6a74a2a85d935ab08bd802ce2 | steve1281/numpy_lessons | /lesson8.py | 613 | 3.765625 | 4 | import numpy as np
# Re-organizing Arrays
before = np.array([[1,2,3,4],[5,6,7,8]])
print(f"before:\n{before}")
print(f"before.shape: {before.shape}")
after = before.reshape((8,1))
print(f"after:\n{after}")
print( f"after.reshape(2,2,2):\n{after.reshape(2,2,2)}")
v1 = np.array([1,2,3,4])
v2 = np.array([5,6,7,8])
pri... |
08f88e42a369d339d135957e8e4088a820344469 | imsure/tech-interview-prep | /py/leetcode_py/887.py | 1,835 | 3.640625 | 4 | class Solution:
def projectionArea(self, grid):
"""
Note: grid is N * N
Top projection: any grid[i][j] > 0 will be projected with area of 1
Side projection: the projected area for each row would the largest element in the row
Front projection: the projected area for each col... |
2093ef811cac5f253565dbb8e1f526c4256e97f6 | imsure/tech-interview-prep | /py/leetcode_py/125.py | 902 | 3.859375 | 4 | class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
words = s.split(sep=' ')
for index, word in enumerate(words):
# word = word.strip('.,:!-@&*^%$#~()_+=?|\/[]{}<>')
new_word = ''
for c in word:
... |
df88399d2267b7bcdc296ecc4ade087a066cb078 | imsure/tech-interview-prep | /foobar2/i_love_lance_janice/solution.py | 395 | 3.546875 | 4 | def answer(s):
ans = []
for c in s:
if 'a' <= c <= 'z':
deciphered = ord('z') - (ord(c) - ord('a'))
ans.append(chr(deciphered))
else:
ans.append(c)
return ''.join(ans)
if __name__ == '__main__':
print(answer("wrw blf hvv ozhg mrtsg'h vkrhlwv?"))
... |
35612faf608a4cb399dacffce24ab01767475b35 | imsure/tech-interview-prep | /py/fundamentals/sorting/insertion_sort.py | 775 | 4.15625 | 4 | def insertion_sort(array):
"""
In place insertion sort.
:param array:
:return:
"""
n = len(array)
for i in range(1, n):
v = array[i]
k = i
j = i - 1
while j >= 0 and array[j] > v:
array[j], array[k] = v, array[j]
k = j
j -... |
5f087f1d4845f1f37690f819bf4b5140e40a07c9 | imsure/tech-interview-prep | /py/fundamentals/recursion/fast_exp.py | 289 | 3.828125 | 4 | def fast_exp(a, n):
"""
Compute a^n using recursion.
:param a:
:param n:
:return:
"""
if n <= 1:
return a
m = n // 2
a1 = fast_exp(a, m)
a2 = a1
if n % 2:
a2 *= a
return a1 * a2
print(fast_exp(2, 5))
print(fast_exp(5, 4)) |
1136682acbd0525dbcd29a6c5a371358d74fc17e | imsure/tech-interview-prep | /py/leetcode_py/contest/84/833.py | 1,009 | 3.625 | 4 | class Solution:
def findReplaceString(self, S, indexes, sources, targets):
"""
:type S: str
:type indexes: List[int]
:type sources: List[str]
:type targets: List[str]
:rtype: str
"""
ans = ""
step = 0
flag = False
index_ = -1
... |
64436397f625a3161f922a74794f3615bc883b0f | imsure/tech-interview-prep | /py/leetcode_py/894.py | 1,175 | 3.65625 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def _preorder(self, nodes, node):
if node is None:
nodes.append(None)
return
nodes.append(node.val)
self._preorder(... |
60f40c5aa23d54e3030b966d36ed9fc17d2c9cd2 | imsure/tech-interview-prep | /py/leetcode_py/408.py | 2,422 | 3.765625 | 4 | class Solution:
def validWordAbbreviation(self, word, abbr):
"""
:type word: str
:type abbr: str
:rtype: bool
"""
if len(abbr) > len(word):
return False
max_digit = len(word)
full_word = ''
i = 0
j = 0
while i < len... |
6d1f5dc5c87bee60a607a4ac557315a06211f833 | imsure/tech-interview-prep | /py/leetcode_py/contest/100/896.py | 530 | 3.578125 | 4 | class Solution:
def isMonotonic(self, A):
"""
:type A: List[int]
:rtype: bool
"""
diff = [0]
for i in range(len(A) - 1):
diff.append(A[i] - A[i+1])
pred_pos = [d >= 0 for d in diff]
pred_neg = [d <= 0 for d in diff]
return all(pre... |
13b4110c187ef07b8061e11bee0ed371e88d46cc | madhurlittu/Python_is_Easy_Pirple | /Homework Assignmentt #4.py | 641 | 3.671875 | 4 | myUniqueList = []
myRejectList = []
AddValue = False
def addRejectValue(Var):
#adding Rejected(Non unique or repeated values) Values to a separate List
return myRejectList.append(Var)
def addItem(Var):
if Var in myUniqueList:
addRejectValue(Var)
AddValue = False
print("... |
a9ce0b5d396227814705133ae6d5cf01b558af28 | saigen007/python-programmer | /beginner level/sum of first k.py | 206 | 3.703125 | 4 | n=int(input("enter the number1"))
k=int(input("enter the number2"))
d=[]
sum=0
for i in range(0,n):
e=int(input("enter the list of element "))
d.append(e)
for j in range(0,k):
sum=sum+d[j]
print(sum)
|
86f86a7ea62fe71527b92f8f4765b70fd86226ac | saigen007/python-programmer | /beginner level/hello in n time .py | 94 | 3.734375 | 4 | a=raw_input("enter the string")
b=input ("enter the count")
for i in range(0,b):
print(a)
|
a6bfdf36b32e887e04ec53786d472b97d9ea6c96 | rgoggins/NLP_question_project | /tokenizer.py | 557 | 3.5 | 4 | from textblob import TextBlob
class Tokenizer:
def __init__(self, input_file):
f = open(input_file, "r+", encoding="utf-8")
text = f.read()
self.blob = TextBlob(text)
# for sentence in self.blob.sentences:
# print(sentence.sentiment.polarity)
### Below are the basics... |
f9178b2e3d72690dfd99d87c0b86034f99fe66cc | pkuipers1/PythonAchievements | /Les04/Loops.py | 1,427 | 3.546875 | 4 | import random
isRunning = True
while (isRunning == True):
print("herhaal!")
if ( random.randrange(0, 2) == 1 ):
isRunning = False
else:
print("Doe als laatste dit")
print("Einde programma")
lijstA = ["tekst", 1, True, 44.05]
lijstB = ["dit","is","een","reeks","tekst"]
print(lijstA)
print(lijst... |
e8df05f41d767b0aa20a406ec094724e37ab23c1 | pkuipers1/PythonAchievements | /Les03/deeplyNested.py | 662 | 3.921875 | 4 | #Vertaal de onderstaande zin naar python code en gebruik daarbij het nesten van if en
#else statements en indien gewenst ook logische operatoren:
#Als ik honger heb en ik geen zin heb om te koken dan bestel ik pizza tenzij er
#nog een kliekje in de koelkast ligt. Dan eet ik die op. Als ik geen geld heb ga ik toch koke... |
4b1ca78ac72c21a86568c94e77e2b1a1eead899d | pkuipers1/PythonAchievements | /Les02/stutterSimulator.py | 247 | 3.828125 | 4 | def Convert(string):
li = list(string.split(" "))
return li
print("Geef een zin op om te converteren en druk op enter:")
str1 = input()
list = Convert(str1)
for i in (list):
if len(i) > 3:
list[list.index(i)] = "abc"
print(list)
|
111204f68a044d9a3f7c84e85d91da8bf9340110 | maitejc/complejos_per | /complejo.py | 966 | 3.734375 | 4 | import unittest
class Complejo(object):
def __init__(self, real, imag=0.0):
self.real = real
self.imag = imag
def multiplicacion(self, otro):
result = Complejo((self.real*otro.real-self.imag*otro.imag),(self.imag*otro.real+self.real*otro.imag))
return result
... |
4acf557ce0ae21d4beb2759fb49ed647c9b82f68 | CaptainSpam/autonifty | /tag/NullTag.py | 635 | 3.84375 | 4 | from Tag import Tag
class NullTag(Tag):
'''
A NullTag acts as if this weren't a tag, inserting the literal tag back into
the HTML. This is an alternative to InvalidTag, which presents an error
back to the user.
'''
def __init__(self):
super(NullTag, self).__init__()
self._tagna... |
722c01d65ec8fffe1988b5e54a400858e8684d1b | JUANGMONROY/Taller-de-Software-I---PC2- | /principal.py | 1,035 | 4.09375 | 4 | #Ejercicio 4 con su libreria
import numpy as np
def crea_arreglo():
n = np.random.randint(5,21,size=(20,20)) #Creo mi matriz con valores aleatorios
print("============================Original============================")
print(n) #Imprimo la matriz original
print("======================================... |
41684f8b8c9ddf80862ad56b52a96263ac84e49a | lithiumdenis/PythonTSP | /PythonTSP/PythonTSP.py | 7,576 | 3.5625 | 4 | import math
import random
# Модель города
class City:
def __init__(self, x, y):
self.x = x
self.y = y
def getX(self):
return self.x
def getY(self):
return self.y
def distanceTo(self, city):
xDistance = math.fabs(self.x - city.x)
yDistance = math.fabs(s... |
11e7b5e6f323eac454eac5f842fa506a73a5ac37 | Bngzifei/PythonNotes | /老男孩/重点概念/new方法.py | 765 | 3.96875 | 4 | # -*- coding: utf-8 -*-
# @Author: Marte
# @Date: 2019-05-09 16:17:08
# @Last Modified by: Marte
# @Last Modified time: 2019-05-09 16:41:00
class Person(object):
"""Silly for Person"""
def __new__(cls,name,age):
print("__new__方法被调用")
return super(Person,cls).__new__(cls) # python3这里__new... |
812fd001fc7659542693a817586cd49b9ee90c47 | Bngzifei/PythonNotes | /Python数据可视化/Python Matplotlib plot函数用法:生成折线图.py | 3,554 | 3.734375 | 4 | # Python Matplotlib plot函数用法:生成折线图
"""
Matplotlib 的用法非常简单,对于最简单的折线图来说,程序只需根据需要给出对应的 X 轴、Y 轴数据,调用 pyplot 子模块下的 plot() 函数即可生成简单的折线图。
假设分析《C语言基础》这本教程从 2013 年到 2019 年的销售数据,此时可考虑将年份作为 X 轴数据,将图书各年销量作为 Y 轴数据。程序只要将 2013~2019 年定义成 list 列表作为 X 轴数据,并将对应年份的销量作为 Y 轴数据即可。
例如,使用如下简单的入门程序来展示这套教程从 2013 年到2019 年的销售数据。
"""
import ... |
5a50cf6af5e761ba0d7eb8ef1181d678c7335e88 | Bngzifei/PythonNotes | /学习路线/2.python进阶/预习/day06协程.py | 15,077 | 4 | 4 | """
迭代:可以使用for遍历(或者更直接一点,这个对象是否内部有__iter__()方法)
可迭代对象:使用for循环遍历取值的对象叫可迭代对象.<列表,元组,字典,集合,range,字符串,文件对象>
"""
"""
判断对象是否是可迭代对象
记住:res/ret都是result的简写,结果之意
"""
import collections
# result = isinstance((3, 5), collections.Iterable) # 是
# print(result)
# print(isinstance([3, 5], collections.Iterable)) # 是
# print(isi... |
db160f1b741178589e3b097dfdb4d46f39168350 | Bngzifei/PythonNotes | /学习路线/1.python基础/day09/06-str方法.py | 608 | 4.21875 | 4 | """str()就是可以自定义输出返回值,必须是str字符串"""
class Dog:
def __init__(self, name):
self.name = name
def __str__(self): # 把对象放在print()方法中输出时,就会自动调用str()方法
return '呵呵呵%s' % self.name # 只能返回字符串
# overrides method :覆盖方法 重写了
dog1 = Dog('来福')
print(dog1) # 如果将str()方法注释掉,把对象放在print中输出时,默认输出的是对象的内存地址 <__main__.Dog object at... |
86355adf38da90a7718e850725fbb132724e8c6a | Bngzifei/PythonNotes | /学习路线/2.python进阶/day14/06-pymysql实现增删改.py | 1,099 | 3.640625 | 4 | """
1.>创建连接connection
2.>获取cursor游标
3.>增删改查等操作
4.>commit()提交
5.>关闭cursor游标
6.>关闭连接connection
"""
import pymysql
# 1.创建和数据库服务器的连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='password', database='python_test_1',
charset='utf8')
# 2.获取游标
cur = conn.cursor()
# 3.执行sql
sql = 'update s... |
aeb6ee9a0bacfe9a1ca84b56d17d5d58c340f37b | Bngzifei/PythonNotes | /学习路线/2.python进阶/day04/老师版本/03-TCP服务器.py | 1,136 | 3.546875 | 4 | import socket
# 1 创建服务器套接字<接受客户端的连接请求的套接字>
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 2 绑定端口
server_socket.bind(('', 9999))
# 3 安装客户服务系统-> 将套接字设置为被动套接字<被动接受连接 默认主动>; 设置等待服务区的大小
server_socket.listen(128)
# 4 从等待服务区取出一个客户端用以服务 ---> 接受一个客户端连接
# 返回值是一个元组 有两个元素 结构: (客户端套接字对象<分机>, (客户端IP, 端口))
cli... |
3433f9ced9c3b346f7a5e4ccc02fdbd58dd7f111 | Bngzifei/PythonNotes | /流畅的Python笔记/支持函数式编程的包-operator模块.py | 1,505 | 3.546875 | 4 | """
得益于operator和functools等包的支持,函数式编程风格也可以信手拈来.
operator模块:
在函数式编程中,经常需要把算术运算符当作函数使用.例如,不使用递归
计算阶乘.求和可以使用sum函数.但是求积则没有这样的函数.我们可以
使用reduce函数,但是需要一个函数计算序列中两个元素之积.
operator模块为多个算术运算符提供了对应的函数,从而避免编写lambda
这种平凡的匿名函数.使用算术运算符函数,可以改写成下面的...
"""
# 使用reduce函数和一个匿名函数计算阶乘
from functools import reduce
def fact(n):
r... |
09e92f5e1217519f985701f2a60369e60933aa91 | Bngzifei/PythonNotes | /学习路线/1.python基础/day08/04-文件的操作.py | 2,096 | 4 | 4 | """文件的作用:
文件作用:持久化数据
文件操作:打开文件,关闭文件 读取,写入(编辑的意思)
打开了要记得关闭,否则内存放不下了就卡住了,最后就会蓝屏
专业名词称为内存泄露(就是内存中的数据一直没有释放)
w:write 写入 文件不存在会自动创建,如果存在会覆盖(替换掉了),文件定位在最前面(最后面也对)
r:read 只读 只读方式打开文件时,如果文件不存在会报错.文件定位在最前面
a:add 末位添加 如果文件不存在,创建,如果存在,则在文件中的字符末位添加.文件定位在最后面.
r+:可读可写
w+:可读可写
open()如果不写打开模式,默认是只读方式 r
用来存储数据
大脑存储的都是临时数据
各式各样的... |
e3d36397e4ba0307b0574963d8bfddbed8d12ef0 | Bngzifei/PythonNotes | /学习路线/1.python基础/day10/09-多继承.py | 1,608 | 4.34375 | 4 | """
C++ 和Python 支持多继承,其他语言不支持
发现规律找规律记,记住区别.初始化只是一次.再次调用init()方法就是和普通的方法调用没区别了.
多态依赖继承.
鸭子类型不依赖继承.
Python中没有重载一说,即使同名函数,方法,出现2次后,第2次的慧覆盖掉第1次的.在一个类里面只能有一个,通过修改参数来进行需要的变化.
同名属性和同名方法只会继承某个父类的一个.继承链中挨的最近的那个.
"""
class Dog:
def eat(self):
print('肉')
def drink(self):
print('水')
class God:
def fly(self):
p... |
d8c4501a2f890f7e63f7e08444204882e45cef5c | Bngzifei/PythonNotes | /学习路线/1.python基础/day03/01-猜拳游戏.py | 970 | 4.1875 | 4 | """
石头1剪刀2布3 猜拳游戏
import random # 导入生成随机数模块
同行的注释时: #号和代码之间是2个空格,#号和注释内容之间是1个空格 这是PEP8的编码格式规范
"""
import random # 导入生成随机数模块
# print(random.randint(1,3)) # 生成1,2,3其中的某一个 以后的才是左闭右开,前小后大,只能生成整数 区间: 数学意义上的()是开区间 ,[]是闭区间.取值规则是:取闭不取开.这里的random.randint(n,m)实际上是n<= 所取得值 <= m.原因是内置函数写死了.
player_num = int(input('请出拳 石头(1)... |
279e7cd4a60f94b9e7ff20e2d16660850f6a76cb | Bngzifei/PythonNotes | /学习路线/1.python基础/day06/01-参数混合使用.py | 1,040 | 4.5 | 4 | print('参数补充:')
"""
形参:位置参数(就是def func(a,b):),默认参数(就是def func(a = 5,b = 9):),可变参数(就是def func(*args):),字典类型的可变参数(就是def func(**kwargs):)
实参:普通实参,关键字参数
形参使用顺序:位置参数 -->可变参数 -->默认参数 -->字典类型可变参数
实参使用顺序:普通实参 ---> 关键字参数
"""
"""位置参数和默认参数混合使用时,位置参数应该放在默认参数的前面"""
"""位置参数和可变参数混合使用时位置参数在可变参数的前面"""
#
#
# def func1(a, *args):
# ... |
6745b15829bcefa04c7dec0c5f53f5bfede8d359 | Bngzifei/PythonNotes | /流畅的Python笔记/继承的优缺点/多重继承的真实应用.py | 6,063 | 3.78125 | 4 | """
多重继承的真实应用
多重继承能发挥积极作用.
的<<设计模式:可复用面向对象软件的基础>>一书中的适配器模式用的就是多重继承,因此使用多重继承肯定没有错.
在Python标准库中,最常使用多重继承的是collection.abc包.这没什么问题,毕竟连Java都支持接口的多重继承,而抽象基类就是接口声明,只不过它可以提供具体方法的实现.
处理多重继承
......我们需要一种更好的,全新的继承理论.例如,继承和实例化混淆了语用和语义.
继承有很多用途,而多重继承增加了可选方案和复杂度.使用多重继承容易得出令人费解和脆弱的设计.我们还没有完整的理论.下面是避免把类图搅乱的一些建议.
1.把接口继承和实... |
1526a00478f0df90e8f460f4d1d5209dd11148ae | Bngzifei/PythonNotes | /学习路线/2.python进阶/day13/06-with补充@contextmanager.py | 1,585 | 3.53125 | 4 | """
提供了 创建资源/销毁资源 就是上下文管理器
"""
class myFile:
"""文件类,取代open类,和open类相似"""
def __init__(self, name, mode):
self.name = name
self.mode = mode
def __enter__(self): # 获取资源
"""这是提供资源的上文环境,提供资源 给as后面的变量"""
print('正在进入上文获取资源')
self.file = open(self.name, self.mode)
return self.file
def __exit__(self, exc... |
ff00c2910d1e70185bdac607b91b133295751b2d | Bngzifei/PythonNotes | /老男孩/内置函数/reduce函数.py | 1,131 | 3.703125 | 4 | """
reduce()函数:在py2中直接使用就行,在py3中需要从模块中导入才能使用
就是将一个列表中的元素经过处理 合到一起,最终得到一个元素
map()函数是将一个列表经过处理,最后得到的还是这个列表,只是这个列表中的元素经过了一定的处理
filter()是将一个列表中的某些元素进行筛选过滤,剔除掉不符合条件的元素,最终得到的还是这个列表,列表中的元素是符号条件的.
需求:
"""
# from functools import reduce
# num_l = [4, 2, 3, 100]
# res = 0
# for num in num_l:
# res += num
# print(res)
... |
5149018a67ac854d93a1c553f315b0b44858848a | Bngzifei/PythonNotes | /学习路线/1.python基础/day05/11-函数的参数补充.py | 2,020 | 4.15625 | 4 | """
形参:有4种类型,位置参数,默认参数(缺省参数),可变参数(不定长 参数).字典类型可变参数
实参:2种类型 普通实参,关键字参数
"""
"""位置参数:普通参数 实参和形参位置数量必须一一对应"""
# def func1(num1, num2):
# print(num1)
#
#
# func1(10, 20)
"""
默认参数(缺省参数): 如果某个形参的值在多次使用时,都是传一样的值,我们可以把此参数改成默认参数
默认参数如果没有传递实参就用默认值,如果传递了实参就使用传递来的实参
默认参数必须放在非默认参数的后面.除非均是默认参数
"""
# def func2(a, b=2):
#... |
d46384116afab32ac07c47a230feed8e5ba7adbc | Bngzifei/PythonNotes | /面试问题/20-算法排序/快速排序/快速排序.py | 1,310 | 3.78125 | 4 | # -*- coding: utf-8 -*-
def quick_sort(alist, start, end):
"""快速排序"""
# 递归退出的条件
if start >= end:
return
# 设定起始元素为要寻找位置的基准元素
mid = alist[start]
# low 为list左边的 从左向右移动的索引值
low = start
# high是list右边从右向左移动的索引
high = end
# 记住:循环中的判断也是实现过滤的功能.即满足了才执行循环体,
# 不满足直接跳过循环体.往下执行即可
... |
b1daf85e10927cea16193f56f9de38676bf6ef37 | Bngzifei/PythonNotes | /学习路线/2.python进阶/day05/08-多线程共享全局变量.py | 821 | 3.796875 | 4 | """
验证多线程是否共享全局变量
"""
import threading
import time
g_number = 100
def func1():
"""线程1 对全局变量 + 11"""
time.sleep(1)
global g_number
g_number += 11 # 内部使用外部,需要声明全局变量
print('线程1:', g_number)
def func2():
"""线程2 给全局变量 + 3"""
for i in range(10):
global g_number
g_number += 3
print('线程2:', g_number)
tim... |
cd1d6e0c0635b6b37c68208de4e24a309389a063 | Bngzifei/PythonNotes | /流畅的Python笔记/对象引用,可变性和垃圾回收/函数的参数作为引用时.py | 1,999 | 3.53125 | 4 | """
Python唯一支持的参数传递模式是共享传参.多数面向对象语言都采用这一模式.
共享传参指函数的各个形式参数获得实参中各个引用的副本.也就是说,函数内部的
形参是实参的别名.
这种方案的结果是,函数可能会修改作为参数传入的可变对象,但是无法修改那些对象
的标识(即不能把一个对象替换成另一个对象)
函数可能会接收到的任何可变对象.
不要使用可变类型作为参数的默认值.
可选参数可以有默认值,装饰Python函数定义的一个很棒的特性,这样我们的API在进化的同时能保证向后兼容.然而,我们应该避免使用可变的对象作为参数的默认值.
出现这个问题的根源是,默认值在定义函数时计算(通常在加载模块时),因此默认值变成了函数对... |
e949b40b28311ae4d3c16a83cc9427c4e967a9a3 | Bngzifei/PythonNotes | /学习路线/1.python基础/day05/09-局部变量和全局变量.py | 1,325 | 3.921875 | 4 | print('局部变量和全局变量:')
"""
形参:占位.接收数据
局部变量:在函数内部定义的变量叫局部变量,它只能在定义它的那个函数内部使用
形参尽量不要和局部变量同名,若同名,优先使用局部变量(所以在函数内部的变量和形参同名时,形参那里显示灰色,表示这个形参未使用)
在函数内部给一个变量赋值默认就是定义一个新的局部变量
尽可能使用局部变量,少用全局变量
降低耦合性
局部变量只要函数调用完了,变量(内存地址)就释放掉了,局部变量就不存在了
全局变量:函数外部定义的变量,可以在全局变量定义之后的.py文件部分使用.<理解:就是这个变量被定义为全局变量之后,这个.py文件中在这个全局变量定义之后的代码范围,均可以使用这个全... |
3c6a9c97e701025f33df74fe1986227869302854 | Bngzifei/PythonNotes | /learnpython100day/类的继承和子类的初始化.py | 1,570 | 4.0625 | 4 | # -*- coding: utf-8 -*-
# @Author: Marte
# @Date: 2019-05-10 11:07:29
# @Last Modified by: Marte
# @Last Modified time: 2019-05-10 11:24:21
#-- 类的继承和子类的初始化
# 1.子类定义了__init__方法时,若未显示调用基类__init__方法,python不会帮你调用。
# 2.子类未定义__init__方法时,python会自动帮你调用首个基类的__init__方法,注意是首个。
# 3.子类显示调用基类的初始化函数:
class FooParent(object):
... |
d04ec4a81ac5afdebfbe8b67a08004d88521426c | Bngzifei/PythonNotes | /学习路线/1.python基础/day03/02-while循环.py | 1,183 | 4.0625 | 4 | print('媳妇,我错了!') # ctrl + d 复制并粘贴当前光标所在行代码或选中区域的代码,效果就是将复制粘贴快捷键合并在一起了.这里要注意光标的起始位置,否则会混在一起
"""
while循环的作用:让指定的代码重复执行指定的次数
使用while循环四步:
1.定义一个计数的变量 (也就是设置一个能够终止循环的条件变量)
2.while条件:只要条件为True就会执行while内部的代码
3.在while内部写需要重复执行的代码
4.修改计数变量的值
在学了for循环之后,基本不会用到while了.除了在遇到无限循环的情况下需使用while True break(continue) 进行某种条件下的终止循环进行... |
557903c0a95e4cb6cf8510a84b1149a505f4bbf2 | Bngzifei/PythonNotes | /老男孩/重点概念/set集合操作.py | 1,399 | 3.78125 | 4 | """
集合:无序,不重复
作用:1.>去重 2.> 关系测试<测试两组数据之间的交集,差集,并集,对称差集等关系>
可变类型的集合的更新操作:
add:添加元素
update:更新,添加
remove:删除集合中指定的元素
del:删除集合本身,即把集合这个容器删除
"""
# a = {1, 2, 3, 4, 5, 6, 7}
# b = {11, 12, 13, 4, 15, 6, 7}
#
# print(a.intersection(b)) # 交集<二者均有的元素> {4, 6, 7}
#
# # {1, 2, 3, 5}
# print(a.difference(b)) # 差集<所有属于a且不属于b的元素构成... |
0d05cf8e33a5e0212ae866011f1c251414b030b4 | Bngzifei/PythonNotes | /学习路线/1.python基础/day10/10-多态和鸭子类型.py | 1,890 | 4.03125 | 4 | """
多态:需要使用父类的对象的地方,也可以使用子类的对象.但是反过来就不可以了.该使用子类对象的地方,不可以使用父类对象.因为父类中没有子类的方法和属性.
多态在其他语言中的定义:用父类的指针指向子类的对象.
多态:明确需要父类对象完成的地方,也可以使用子类对象完成. 因为子类继承了父类的方法属性之后也可以使用子类来表示父类的一些操作.
动态语言中是没有多态一说的,因为有数据类型的限制.Python中没有多态一说,因为Python中的参数啊,变量之类的没有数据类型的限制.
但是有个替代品-->鸭子类型 Python 语言使用鸭子类型来替代多态的.
父类引用子类
鸭子类型:只要能完成想要的的操作.不关注对象的类型,... |
b36169cf1712dca276d8bc33bca89412500342d1 | Bngzifei/PythonNotes | /学习路线/1.python基础/day04/09-切片.py | 834 | 4.1875 | 4 | """
切片:取出字符串的一部分字符
字符串[开始索引:结束索引:步长] 步长不写,默认为1
下一个取得索引的字符 = 当前正在取得字符索引 + 步长
其他语言叫截取
步长:1.步长的正负控制字符串截取的方向 2.截取的跨度
"""
str1 = "hello python"
# print(str1[0:5])
# print(str1[:5]) # 如果开始索引为0,可以省略
# str2 = str1[6:12]
# str2 = str1[6:] # 如果结束索引最后,可以省略
# print(str2)
# list1 = [11, 12, 14]
# print(list1[-1]) # 负索引,倒着数,比较方便
... |
258f80cccb19730b8ad4b8f525b9fcac8ab170f2 | Bngzifei/PythonNotes | /学习路线/2.python进阶/day11/02-闭包.py | 1,079 | 4.34375 | 4 | """
closure:闭包的意思
闭包特点:
1.>函数的嵌套定义,就是函数定义里面有另外一个函数的定义
2.>外部函数返回内部函数的引用<引用地址>
3.>内部函数可以使用外部函数提供的自由变量/环境变量 <顺序是先去找自己的位置参数,看看是否有同名,如果没有就向外扩展一层,继续这个过程.直到找到>
这就是闭包的三个特点
概念:内部函数 + 自由变量 构成的 整体 这是IBM 开发网站的一个说法
理解:内部函数 + 外部函数提供给内部函数调用的参数.
"""
def func(num1):
# 外部函数 的变量称之为自由变量/环境变量 内部函数也可以使用
print('in func', num1)
d... |
40089a436572a1941b968a01b2e40f75924613e4 | Bngzifei/PythonNotes | /Python数据可视化/Python Matplotlib绘制柱状图(bar和barh函数)详解.py | 1,580 | 3.5625 | 4 | # Python Matplotlib绘制柱状图(bar和barh函数)详解
# 下面程序使用柱状图来展示《C语言基础》和《Java基础》两套教程历年的销量数据。
import matplotlib.pyplot as plt
import numpy as np
# 构建数据
x_data = ['2012', '2013', '2014', '2015', '2016', '2017', '2018']
y_data = [58000, 60200, 63000, 71000, 84000, 90500, 107000]
y_data2 = [52000, 54200, 51500, 58300, 56800, 5950... |
cdab2900e3495440613dfeea792f09953078fa1a | Bngzifei/PythonNotes | /学习路线/1.python基础/day03/07-定义列表.py | 530 | 4.1875 | 4 | """
存储多个数据,每个数据称之为元素
格式:[元素1,元素2...]
列表中尽可能存储同类型数据,且代表的含义要一致.实际上可以存储不同类型的数据
获取元素:列表[索引]
常用的标红:整理一下好复习
增.删.改.查
"""
list1 = ['11', '22', 18, 1.75, True]
print(type(list1))
print(list1[4])
l1 = list()
print(l1)
# IndexError: list index out of range
# print(list1[8]) 索引超出list范围,报错
list1[0] = '你大爷' # 修改元素的值
p... |
f9b67b7b3303f4685940632e731e7cfc9bf4d392 | Bngzifei/PythonNotes | /学习路线/1.python基础/day07/01-set.py | 1,232 | 4.03125 | 4 | """
set 无序集合
特点:没有索引, 里面的数据不会有重复
很少使用来表示数据
如果想让列表,元组中没有重复的元素可以把它们转换成set类型
不能转字典类型,因为格式不一样
set 格式:{元素1,元素2}
"""
# set1 = {1, 2, 33, 4, 4, 55}
# print(set1)
# print(type(set1))
# #
# list1 = [1, 23, 4, 5, 3, 66, 2, 333, 3, 3, 3]
# print(list1)
# set2 = set(list1) # 影响了List的顺序
# print(set2)
# 作业:在不影响列表中元素的位置情况下把列表中的数... |
7f492ec8cba3c19ca673c6557694c29785f6826d | Bngzifei/PythonNotes | /学习路线/1.python基础/练习/反恐practice.py | 4,113 | 3.65625 | 4 | """
要求:
1.游戏枪支有不同的型号,并拥有不同的伤害
2.枪支可以添加一定数量的子弹
3.枪支可以射击敌人,射击敌人时,如果子弹数量为0,则提示玩家;如果有子弹,会减少子弹,如果击中敌人,会让敌人受伤
4.输出枪支信息时,可以显示枪支的型号、伤害、子弹数量 ————————————————————————————————————————————————
5.游戏玩家分为警察和匪徒两种角色,玩家拥有自己的枪支和血量,可以攻击敌人
6.玩家攻击敌人时,如果没有枪,则提示玩家;如果有枪,则检查枪支是否有子弹,有子弹则使用枪支射击敌人,没有子弹则自动给枪支添加子弹
7.玩家被击中会受伤,减血量为枪支的伤害,提示玩家受伤并显示当前血量... |
ba81ff36d550b951451133274d74ff26ff087415 | Bngzifei/PythonNotes | /面试问题/9-设计模式/装饰器模式/example01.py | 1,173 | 3.640625 | 4 | # -*- coding: utf-8 -*-
import time
def get_time(func): # 这里只能接收一个参数,即使写成了*args **kwargs的形式
"""对函数运行时间进行统计"""
print('in get_time')
def inner(*args, **kwargs): # 传参数,打包 内部函数可以接收任意参数
t1 = time.time()
# 解包参数 如果函数有返回值,暂时先保存,执行结束再返回
# 这里的* 和** 是解包的作用,将刚刚打包的参数进行解包
res = func... |
9b8bc234ae05a1a1fc3ed18009c24c833117b9a1 | Bngzifei/PythonNotes | /面试问题/20-算法排序/冒泡排序/冒泡排序01.py | 1,210 | 3.953125 | 4 | # -*- coding: utf-8 -*-
# bubble:n. 气泡,泡沫,泡状物;透明圆形罩,圆形顶
# 在打印图形中,外循环控制行数,内循环控制列数<即一行有几个元素>
def bubble_sort(nums):
# 注意:这里的len(nums) - 1不是通常意义的生成元素的索引.形式一样,表示的含义不同.
for i in range(len(nums) - 1): # 外循环控制排序次数,因为是相邻两个进行比较,所以比较次数就是 元素个数 - 1<类似于5个手指有4个空隙>
for j in range(len(nums) - i - 1): # 内循环控制列表下标,即控制... |
6bfd759f220785ad60a3f5ba642fdd2c228d396e | Bngzifei/PythonNotes | /流畅的Python笔记/命令模式.py | 2,530 | 3.65625 | 4 | """
命令模式.这个设计模式也常使用单方法类实现,同样也可以换成普通的函数.
命令模式的目的是解耦调用操作的对象(调用者)和提供实现的对象(接收者).
这个模式的做法是,在二者之间放一个Command对象,让它实现只有一个方法(execute)
的接口,调用接收者中的方法执行所需的操作.这样,调用者无需了解接收者的接口,
而且不同的接收者可以适应不同的Command子类.调用者有一个具体的命令,通过调用
execute方法执行.
命令模式是回调机制的面向对象的替代品.
我们可以不为调用者提供一个Command实例,而是给它一个函数.此时,调用者不用调用
command.execute(),直接调用command()即可... |
0595e7673cca58e05b3b0ad0bb96797a7ac743ab | lizashkredova/studing_hillel | /liza_task_3_hw_15.py | 299 | 3.5625 | 4 | class Context_manager:
def __init__(self, file):
self.file_ = open(file, 'w')
def __enter__(self):
return self.file_
def __exit__(self, exc_type, exc_value, exc_traceback):
self.file_.close()
with Context_manager("text.txt") as file:
file.write("Hi, user") |
d7e890376389e982a0ea7749df18f3cf28513912 | agfor/incd | /incd/incd.py | 2,982 | 3.671875 | 4 | from abc import ABCMeta, abstractmethod
from functools import wraps
def convert_to_list(number):
if isinstance(number, int):
number = str(number)
if isinstance(number, str):
number = [int(d) for d in number]
if not isinstance(number, list):
raise
return number
def convert_to_st... |
ee8fac9200ebf38da13ffd656d0674c8cbbf7682 | harinipradeep/Exercises | /generator_expression.py | 444 | 3.875 | 4 | numbers = [1,2,3,4,5]
#a generator expression(note:This is not a tuple comprehension)
lazy_squares = (x*x for x in numbers)
print(type(lazy_squares))
for i in numbers:
#explicit calling of next
print(next(lazy_squares))
lazy_sum = (x+x for x in numbers)
print(type(lazy_sum))
#implicit calling of next
for i in lazy_su... |
70f10df39e8cbb50c4a19ded136d1dc11a9805a1 | OoCharly/Python-Django | /d03/ex00/geohashing.py | 942 | 3.671875 | 4 | import sys, antigravity
def iscoordinate(lat, long):
if lat in range(-90, 90) and long in range(-180, 180):
return True
return False
def do_the_geohash():
lat = float(input('Latitude(float): '))
long = float(input('Longitude(float): '))
if iscoordinate(lat, long):
dow = input('Dat... |
0c2098012c94768060a7dd900198028db65b0af5 | asw001/thinkful | /pirate_bartenderIM.py | 2,218 | 3.828125 | 4 | #!/usr/bin/python3
import sys
import random
questions = {
"strong": "Do ye like yer drinks strong?",
"salty": "Do ye like it with a salty tang?",
"bitter": "Are ye a lubber who likes it bitter?",
"sweet": "Would ye like a bit of sweetness with yer poison?",
"fruity": "Are ye one for a fruity finis... |
b1b071d240572eb7d033b1f01ab114f344b6c397 | FabioLeonam/exercises | /hacker_rank/linked_list/get_node.py | 871 | 3.53125 | 4 | # Complete the getNode function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def getNode(head, positionFromTail):
counter = 0
pointer = head
while pointer:
counter += 1
pointer = pointer.next
counter -= positionFromTail... |
0458502d932fea0eb3157f196a1342dce6e1edad | FabioLeonam/exercises | /LeetCode/Linked Lists/middle_ll.py | 732 | 3.9375 | 4 | """
876. Middle of the Linked List
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
Example: Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3.
(The judge... |
cbee5074445341df9b25bac958933a614aaf90a2 | samhenryowen/samhenryowen.github.io | /CS160/python/mastermind.py | 860 | 3.546875 | 4 | import random
guesses = 0
d = {1: 'R', 2: 'G', 3: 'B', 4: 'W'}
numbers = [random.randint(1,4) for _ in range(4)]
numbers = [d[n] for n in numbers]
while True:
i = 0
correct = 0
correct_color = 0
guess = input('Enter your guess (XXXX format): ')
for n in numbers:
if n == guess[i]:... |
e523dc0e2480ca3f4237b19abab630eae4521db4 | samhenryowen/samhenryowen.github.io | /CS160/python/funpython/ch5-33.py | 73 | 3.71875 | 4 | i = int(input("Enter an integer: "))
for n in range(i):
print('*'*i) |
5763c1caf72e350b31a2c97886136410a92099b8 | samhenryowen/samhenryowen.github.io | /CS160/python/rockpaperscissors.py | 899 | 3.96875 | 4 | import random
def play():
rnd = random.randint(1,3)
ans = str(input("Rock, paper, scissors? "))
if (ans == "rock"):
if (rnd == 1):
print("Computer plays rock. It's a tie.")
if (rnd == 2):
print("Computer plays paper. You lose.")
if (rnd == 3):
pr... |
5ababf381ed4e9f6cec093fc0c04fe8241a38a3a | zzuberi/projects | /data_structures/bst.py | 6,008 | 3.8125 | 4 | class TreeNode:
def __init__(self, val):
self.val = val
self.right = None
self.left = None
def __str__(self):
return str(self.val)
class BST:
def __init__(self):
self.root = None
def insert(self, val):
if self.root is None:
self.root = Tr... |
9358050b1c9704f0f6689dfbceb7b5cb6113cc4c | zzuberi/projects | /algorithms/transpose.py | 293 | 3.734375 | 4 | test = [[x for x in range(5)], [x for x in range(5,10)]]
new = []
print(test)
# for i in range(len(test[0])):
# for j in range(i, len(test)):
# test[i][j], test[j][i] = test[j][i], test[i][j]
print(list(map(list,zip(*test))))
test = list(map(list,zip(*test[::-1])))
print(test)
|
5203eca42c2f7422a7464954ae2a689897a6095a | caynan/code2040 | /CLI/solver.py | 1,074 | 3.546875 | 4 | from datetime import datetime, timedelta
def solve_reverse_string(to_reverse):
ans = {'string': to_reverse[::-1]}
return ans
def solve_haystack(input_dictionary):
needle = input_dictionary['needle']
haystack = input_dictionary['haystack']
# It's guranteed that there is a needle on the haystack
... |
5202413d080704226dbab372abb29ab21ec3db68 | kundan4U/ML-With-Python- | /ML With python/practice/exception.py | 223 | 3.875 | 4 | try:
x=int(input("Plese enter the first number :"))
y=int(input("Plese enter the second number :"))
z=x/y
print("division is :",z)
except ZeroDivisionError:
print("Plese dont enter Zero")
finally:
print("Good bye") |
c62b9f67f84863d97dc8d324f4015ac4ea7447bd | kundan4U/ML-With-Python- | /ML With python/ASSIGNMENT/p83.py | 260 | 3.796875 | 4 | sentence=input("plese Enter the sentence sentence :")
word=input("Enter word that you want Occurrence :")
a=[]
count=0
a=sentence.split(" ")
for i in range(0,len(a)):
if(word==a[i]):
count=count+1
print("Occurence of the word is : ",count)
|
6a0659619f07bf6325272008f854b70b3fe65900 | kundan4U/ML-With-Python- | /ML With python/ASSIGNMENT/p63.py | 353 | 3.609375 | 4 | class Shape:
def print_shape(self):
print("This is shape")
class Rectangle(Shape):
def print_rect(self):
print("This is rectangular shape")
class Circle(Shape):
def print_circle(self):
print("This is circular shape")
class Square(Rectangle):
def print_square(self):
print("Square is a rectangle")
sq=Square()... |
010a193fc6f5aaaafa374c9da14091eb6a72c655 | kundan4U/ML-With-Python- | /ML With python/ASSIGNMENT/p61.txt | 393 | 3.984375 | 4 | class A:
def sum(self,a,b):
return(a+b)
class B(A):
def sub(self,a,b):
return(a-b)
def mul(self,a,b):
return(a*b)
x=int(input("Plese enter first number : "))
y=int(input("Plese Enter the second number :"))
I=B()
print("Sum of given number is is :",I.sum(x,y))
print("Substration of given number is : "... |
575612d85c08f5a254a32cfb4ed5245b7bfc4100 | n0n4zw0rl6/ericosur-snippet | /python/fib/stupid_factorial.py | 956 | 3.9375 | 4 | #!/usr/bin/env python
import sys
import math
def stupid_factorial(m):
'''
a trivia way to get n! recursively
'''
if m <= 1:
return 1
else:
return m * stupid_factorial(m - 1)
def try3k():
# maybe too deep recursive to calculate n!
n = 3000 # try to get n!
'''
try ... |
58a9147f39b86f6cba4ee6b065a9053b69706df4 | n0n4zw0rl6/ericosur-snippet | /deck/allpoker.py | 2,970 | 3.734375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# use shuffle_array() in fisher_yates_shuffle.py
#from fisher_yates_shuffle import shuffle_array
import random
'''
Var 'card' stands for a card, which is a list contains
[suit, point]. 'Suit' means 'heart', 'spade', 'club' and 'diamond'.
'Point' is in the range of 1 to 13.
... |
55c9fd9a044675679507d72e9b70e08372c9477b | n0n4zw0rl6/ericosur-snippet | /pi/monte_carlo_pi.py | 334 | 3.8125 | 4 | #!/usr/bin/env python
'''
Monte Carlo method to calculate pi
from comments of:
http://programmingpraxis.com/2009/10/09/calculating-pi/2/
'''
from random import random
def pi(n):
return 4*float(sum(1 if (random()**2 + random()**2) <= 1 else 0 for i in range(n)))/n
if __name__ == '__main__':
print "approx pi =... |
baef60e9ba798700ebcf90cb5a7c70b7004fc09a | shilinlee/learn-python | /functional_programming/filter.py | 294 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author = 'shilinlee.com'
#返回奇数
def is_odd(n):
return n%2==1
L = list(filter(is_odd,[1,2,3,4,5,7,8,12,15]))
print(L)
#去掉空字符串
def not_empty(s):
return s and s.strip()
L = list(filter(not_empty,['A','','B',None,'C',' ']))
print(L) |
8a527fd405d5c59c109252f58527d9b4d5e73eeb | sahaib9747/Random-Number-Picker | /App_Manual.py | 607 | 4.125 | 4 | # starting point
import random
number = random.randint(1, 1000)
attempts = 0
while True: # infinite loop
input_number = input("Guess the number (berween 1 and 1000):")
input_number = int(input_number) # converting to intiger
attempts += 1
if input_number == number:
print("Yes,Your guess is c... |
76b768b1a2c81d7f54b65dcc3842245422cfa4ec | pradeep-axl/TwitterCollections | /utilities/common_utils.py | 1,900 | 3.796875 | 4 | import json
import os
def generate_file_path(directory: str, file_name: str):
"""
Helper function to return os independent file path
:param directory:
:param file_name:
:return:
"""
return os.path.join(os.getcwd(), directory, file_name)
def load_json_file(file_path: str):
"""
fun... |
50014e9a58d561e67d95d349f20f5214de3815d2 | bleimaulani6/yogaMaster | /yogaMaster/evaluate_ch.py | 71,657 | 3.828125 | 4 | import os
import numpy as np
def evaluate_pose(pose_seq, exercise):
"""Evaluate a pose sequence for a particular exercise.
Args:
pose_seq: PoseSequence object.
exercise: String name of the exercise to evaluate.
Returns:
correct: Bool whether exercise was performed correctly.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.