blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
7d48479e7507c8eef3a8139a8b215b5f21eff583 | Chestermozhao/Notes | /algorithms_practice/35.py | 523 | 4 | 4 | """Leetcode 35 Easy search insert position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
"""
class Solution:
def searchInsert(s... |
954966c866a27a5fb85aeee3cc65702641599c92 | Chestermozhao/Notes | /algorithms_practice/172.py | 660 | 3.5625 | 4 | """Leetcode 172 Easy
Given an integer n, return the number of trailing zeroes in n!.
Follow up: Could you write a solution that works in logarithmic time complexity?
"""
class Solution:
def get_five_count(self, num):
c = 0
five_flag = True
while five_flag:
num = num / 5
... |
7d8ad6a04e664e60376a7967e7ffc653c043e435 | Chestermozhao/Notes | /algorithms_practice/355.py | 5,409 | 4.21875 | 4 | """Design Tweet
- 這題不是自己做的,但是總體來說最難的是取出10筆最新的關注內容
- 透過存入的時候增加時間戳訊息可以達到
"""
import heapq
class Twitter:
def __init__(self):
#Tracks all users of twitter. Key is the user, value is a set the user follows
self.users = {}
#Maps users to all tweets they've made. Tweets are a tuple wher... |
2ef0f1f05261137ea9b4319426804ccccb832534 | Chestermozhao/Notes | /algorithms_practice/82.py | 953 | 3.78125 | 4 | """82. Remove Duplicates from Sorted List II Medium
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0... |
32f4f1fa4e1a09fa2f1259ff39963cf4d5301e2a | Alephanta/Code_learn.python | /Homework_1/Homework1_for3.py | 750 | 3.640625 | 4 | school = [
{'school_class': '1a', 'scores': [5,5,4,4,3,3,2,2]},
{'school_class': '2b', 'scores': [3,2,4,5,5,3,3,3,4,4,4]},
{'school_class': '3c', 'scores': [2,2,2,2,5,5,5,5,4,4,4,3,3]},
]
sum_scores = 0
count = 0
for school_class in school:
scores = school_class['scores']
for number in scores:
... |
fdfc8a32e2aa706a34d4ea92e7b219919b8e0e42 | MPM88/Conjetura-de-collatz-python | /Collatz.py | 376 | 4.0625 | 4 | #Prueba de la conjetura de collatz en Python
def IsEven(Number):
if (Number % 2 == 1):
return False
else:
return True
def CalculateCollatz(Number):
while Number > 1:
if (IsEven(Number) == False):
Number = Number * 3 + 1
print(Number)
else:
Number = Number / 2
print(Number)
Calc... |
9509ff435270fecdaa1d5e01e4e9a9fee84a973c | Erick-ECE/ProblemSolving | /cumulativeSum.py | 211 | 3.90625 | 4 | #Write a function that returns the cumulative sum of elements in a list
def cumulativeSum(l):
c = 0
for i in range(len(l)):
c+=l[i]
l[i]=c
return l
lista=[1,1,1]
cumulativeSum(lista) |
a83edcaefc88185b447477c0181f8f6b7c160121 | Erick-ECE/ProblemSolving | /leetcode/Dynamic Programming/BestTimetoBuyandSellStock.py | 1,021 | 3.96875 | 4 | #Leet Code
# Best Time to Buy and Sell Stock
# Say you have an array for which the ith element is the price of a given stock on day i.
# If you were only permitted to complete at most one transaction
# (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
# Note that you ca... |
719ad69267dc8a19e2fd07b7037ce1eaf02e2816 | Erick-ECE/ProblemSolving | /leetcode/array/singleNumber.py | 318 | 3.703125 | 4 | # Single Number
# given a non-empty array of integers,
# evrery element apears twice except one. Find that single one.
#input= [4,1,2,1,2]
#output= 4
def singleNumber(arr):
single=arr[0]
for i in range(1,len(arr)):
single^=arr[i] # make a bitwise operation (xor) over all the array
return single |
94b93283bc25a7ab4ac56231549b8f0e86758317 | Erick-ECE/ProblemSolving | /anagram.py | 168 | 3.90625 | 4 | # is anagram?
def isAnagram(s,u):
return sorted(s) == sorted(u)
string1= "calabaza"
string2= "labzaaca"
string3= "calabazaaa"
print(isAnagram(string1,string2))
|
762e2612833f558a20a21394e76fb0c928151ca6 | dev-swi2021/algorithm | /2606.py | 864 | 3.515625 | 4 | from collections import deque
# 1번을 통해 바이러스가 전파된 컴퓨터 대수 구하기(컴퓨터 대수에서 1번 컴퓨터 제외)
def bfs(graph, start, visited):
queue = deque([start])
visited[start] = True
count = -1
while queue:
v = queue.popleft()
count += 1
for i in graph[v]:
if not visited[i]:
... |
ebb25b6998bf21815faa79944082816c04d95cb0 | sesantanav/python_basics | /poo.py | 1,415 | 4.25 | 4 | # Programación Orientada o Objetos con Python
# Clases
class NuevaClase:
pass
class Persona:
def __init__(self):
self._nombre = ""
self._edad = 0
# Metódods de la clase
# setters
def setNombre(self, nombre):
self._nombre = nombre
def setEdad(self, edad):
sel... |
ceebe27a41cffcadebc6b170ea711271ba57db8b | RT-Thread/IoT_Board | /examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/urandom.py | 2,934 | 3.65625 | 4 | """
urandom 模块实现了伪随机数生成器。
"""
def choice(obj) -> None:
"""
随机生成对象 obj 中的元数。
- obj:元数列表
示例:
- print(random.choice("DFRobot"))
- R
- print(random.choice("DFRobot"))
- D
- print(random.choice([0, 2, 4, 3]))
- 3
- print(random.choice([0, 2, 4, 3]))
- 3
- print(random.... |
8a310063953794e4ec209ecaa07fe835ed643a31 | RT-Thread/IoT_Board | /examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/ujson.py | 980 | 4.0625 | 4 | """
ujson 模块提供 Python 对象到 JSON(JavaScript Object Notation) 数据格式的转换。
"""
def dumps(obj) -> None:
"""
将 dict 类型转换成 str。
- obj:要转换的对象
示例:
- obj = {1:2, 3:4, "a":6}
- print(type(obj), obj) #原来为dict类型
- <class 'dict'> {3: 4, 1: 2, 'a': 6}
- jsObj = json.dumps(obj) #将dict类型转换成str
- pri... |
0b5896ebdce3a21a636badb78dc9c757dc8af2ae | mariolpantunes/load-balancer | /utils.py | 679 | 3.546875 | 4 | # coding: utf-8
import time
# Leibniz formula for pi
def leibniz_pi_precision(precision=10):
rv = 1
for i in range(precision):
time.sleep(0.001)
if i % 2 == 0:
rv -= 1/(2*(i+1)+1)
else:
rv += 1/(2*(i+1)+1)
return rv * 4.0
# Bailey–Borwein–Plouffe formula
... |
bef803e2740a08daa6cf96dffd11b06f3809999d | kushagraagarwal19/HackerRank-Interview-Preparation-Kit | /String Manipulation/Making Anagrams.py | 382 | 3.90625 | 4 | # https://www.hackerrank.com/challenges/ctci-making-anagrams/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=strings
def makeAnagram(a, b):
count = 0
for char in a:
if char not in b:
count += 1
print(count)
for char in b:
if char not ... |
6294520ff202a7679f70be8f9387053ed01ea0a5 | abjose/hs_metasquares | /game.py | 3,937 | 3.59375 | 4 | #!/usr/bin/env python
"""
Event-driven version of the game.
"""
from grid import Grid
from utils import Point, check_square, get_squares, get_square_score, get_scores
import pprint
"""
TODO:
- Sure it's a good idea to return error messages like this?
- make AI? need to think about how best to interface with...
On... |
77c89304bb992bd8bb04f54ff6e1fb27049efd4f | Crystal9202/Python | /mod14/require_arg.py | 186 | 3.6875 | 4 | # Function definition
def area(length,width): # two parameters
return length*width
# MAIN
# Call function
result = area(15,8) # two require arguments
print('Area =',result)
|
37ec2f98d3ad69591a17d2e7dd1264a75977c204 | IMF0206/pythonexercise | /python/exercise_70.py | 86 | 3.625 | 4 | #jisuan zifuchuan changdu
s = raw_input('enter the string:')
print 'the len of the string is %d' %len(s) |
d9af8252e0d03c486553cf714a25d95b489f61b0 | IMF0206/pythonexercise | /python/python_01.py | 1,117 | 4.03125 | 4 | print "hello world!!"
print r"\\\n\\"
print 3>2
print "Hello %s"%"world"
print "%2d-%02d"%(3,1)
print "%.2f"%3.1415926
print "%s-0%s"%(3,1)
print "%s" %3.1415936
classmates = ["James","Bob","Tom"]
print classmates
print len(classmates)
print classmates[2]
print classmates[-1]
classmates.append("Adam")
print classmates... |
3c992df7316b2a488de59e5cee4598b70875c0a7 | xitizmandal/deep_learning | /test_nn.py | 2,070 | 3.546875 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
tf.reset_default_graph()
#file_name
file_name = "mnist/model.ckpt"
#input_data
mnist = input_data.read_data_sets("mnist",one_hot=True)
#Parameters
batch_size = 128 #batch size
epochs = 20 #number of iterations
learning_rate = 0.01 #lea... |
571cabc2c677642f9da8cc45a4f48c1ddfdd8f31 | CarlosMunozA/Python-inicio | /lists.py | 1,144 | 3.96875 | 4 | lala = [1,23,12,[True,2, 'lala']]
colors=['red','green','white']
numberList = list((1,2,3,4))
#print (type(numberList))
#range crea listas con los número del 1 al 9 en este caso
#r= list(range(1,10))
#print(r)
# print(dir(colors))
# #len=largo de la lista
# print(len(colors))
# print(len(lala))
#pregunta si exist... |
e7131752981f6c5ae0a4a7d86e2a57991f73a8f0 | paxosglobal/dsert | /dsert/__init__.py | 4,067 | 3.5 | 4 |
def assert_valid_dict(to_validate, known_contents={}, known_types={}, excluded_fields=[]):
"""
Take a dict to_validate and validate all known known + unknown fields,
while skipping any excluded_fields
Details of inputs:
- known_contents is a dict with the exact key/value pairs expected in to_val... |
6169cef4dc7e955838551dc59569aa41efc11a23 | harshonyou/SOFT1 | /week2/week2_additionalexercice_3.py | 624 | 4.0625 | 4 | '''
Exercise 3:
A fruit company sells bananas for £3.00 a kilogram plus £4.99 per order for postage and
packaging. If an order is over £50.00, the P&P is reduced by £1.50. Write a script that will take
the number of kilo of bananas as a user input and print the cost of that order.
'''
print('Welcome to the Banana Shop... |
2ec1609c2b80d7c62a86d3dd6f42398772ef099a | harshonyou/SOFT1 | /week7/week7_practical6b_3.py | 653 | 3.96875 | 4 | '''
Exercise 3:
There is a way to add the following functionality to our class Vector.
>>> vector1 = Vector(1, 2, 3, 5, 6, 1)
>>> vector1[2] += 5
>>> print(vector1)
<1.0, 2.0, 8.0, 5.0, 6.0, 1.0>
Search the web to find out how it can be done (I will NOT provide the answer). For method
with undefined number of parameter... |
1e7f67cd95ecd74857bcc0a2aeb4a45e6b13947d | harshonyou/SOFT1 | /week5/week5_practical4b_5.py | 440 | 4.125 | 4 | '''
Exercise 5:
Write a function to_upper_case(input_file, output_file) that takes two
string parameters containing the name of two text files. The function reads the content of the
input_file and saves it in upper case into the output_file.
'''
def to_upper_case(input_file, output_file):
with open(input_file) as x... |
dd0b87ac56156e3f3f7397395752cd9f57d33972 | harshonyou/SOFT1 | /week7/week7_practical6a_6.py | 1,075 | 4.375 | 4 | '''
Exercise 6:
In Programming, being able to compare objects is important, in particular determining if two
objects are equal or not. Let’s try a comparison of two vectors:
>>> vector1 = Vector([1, 2, 3])
>>> vector2 = Vector([1, 2, 3])
>>> vector1 == vector2
False
>>> vector1 != vector2
True
>>> vector3 = vector1
>>>... |
144d4f3348f727f308b555b8d87e8514163de443 | harshonyou/SOFT1 | /week7/rectangle.py | 280 | 3.71875 | 4 | class Rectangle:
def __init__(self,x=0,y=0,w=0,l=0):
self.x = x
self.y = y
self.w = w
self.l = l
pass
def areaRect(self):
return self.w*self.l
pass
r = Rectangle()
r.x = 0
r.y = 0
r.w = 1
r.l = 2
print(r.areaRect()) |
f66c3482a9f8e49a42bc673cd9958379227139d4 | harshonyou/SOFT1 | /week1 and extra/TPOP_pychallange1_advance.py | 313 | 3.875 | 4 | import math
input = int((input("Enter Your Number: ")))
valid = True
lowerlimit = 2
upperlimit = math.ceil(pow(input,1/2))
print(upperlimit)
for x in range(2,upperlimit+1):
if(input%x==0):
valid=False
print('non-prime')
exit()
pass
pass
if(valid):
print( 'prime' ) |
7353b15825873333c5229fb80411f2003b30fcbe | harshonyou/SOFT1 | /week3/week3_practical2_3.py | 1,588 | 4.03125 | 4 | '''
Exercise 3: Cryptography, Caesar Cipher
In cryptography, a Caesar cipher, also known as the shift
cipher, is one of the simplest and most widely known
encryption techniques. It is a type of substitution cipher in
which each letter in the plain text is replaced by a letter some
fixed number of positions down the alp... |
2e0a8282a134cf8cc3a1695aa366ff1348000d01 | harshonyou/SOFT1 | /week3/Answers/week03practical02modelanswers.py | 4,701 | 4.15625 | 4 | ######################### EXERCISE 1 #########################################
# A common error is to reverse the word and compare if it is equal to itself.
# This is an ineficient implementation, it is better to use two pointers
# (indices) moving from both ends and compare if they point to the same
# character.
sen... |
13138f7e7f105cb917d3c28995502f01ace2c46a | harshonyou/SOFT1 | /week4/week4_practical3_5.py | 829 | 4.25 | 4 | '''
Exercise 5: Where’s that bug!
You have just started your placement, and you are given a piece of code to correct. The aim of
the script is to take a 2D list (that is a list of lists) and print a list containing the sum of each
list. For example, given the list in data, the output should be [6, 2, 10].
Modify the co... |
7209b64a1bfbca67fa750370a6b2a2f35f04085b | harshonyou/SOFT1 | /week3/week3_ex1_1.py | 870 | 4.125 | 4 | '''
Exercise 1: Simple while loopsExercise 1: Simple while loops
1. Write a program to keep asking for a number until you enter a negative number. At the end, print the sum of all entered numbers.
2. Write a program to keep asking for a number until you enter a negative number. At the end, print the average of all en... |
5ea0cc693f79322a018bf1a4aa881ee5d722c593 | harshonyou/SOFT1 | /week10/week10_practical10_4.py | 1,875 | 3.5625 | 4 | import math
class Polynomial:
def __init__(self, coefficients):
self._coef = coefficients
def __str__(self):
power=0
output=''
for x in range(len(self._coef)):
if not abs(self._coef[-x-1]) == 0:
output+=('+ ' if self._coef[-x-1]>0 else '- ' )+str(abs(... |
c6de2a405dba8368ea0a94e98a5e66bdcd036652 | yashika0810/Djangorepo | /loop.py | 1,881 | 3.96875 | 4 | '''
avg=0
total=0
count=0
print("Enter the grade(-1 to quit)")
grade=int(input("Please enter the grade"))
while grade!=-1:
total=total+grade
count=count+1
print("Enter the grade(-1 to quit)")
grade=int(input("Please enter the grade"))
if count==4:
break
print("I am outside the loop")
avg=t... |
7defc922a05645b90b9e4d9cbf225a2287b058cd | aspaceo/splay | /set_range_sum.py | 8,041 | 3.6875 | 4 | # python3
from sys import stdin
# Splay tree implementation
# Vertex of a splay tree
class Vertex:
def __init__(self, key, sum, left, right, parent):
(self.key, self.sum, self.left, self.right, self.parent) = (key, sum, left, right, parent)
def hasLeftChild(self):
return self.left is not Non... |
aa57d7e59a5043ada994af4d4e9c3d21f8a5e54d | filfreire/questions-three | /questions_three/vanilla/string_of_sequential_characters.py | 560 | 3.875 | 4 | from string import ascii_letters, digits
LETTERS_AND_NUMBERS = ascii_letters + digits
def string_of_sequential_characters(*, character_count):
if type(character_count) is int and character_count > 0:
loop_count = 0
string = ""
for n in range(character_count):
if loop_count ==... |
eed7acac5dbcaea3f86688b489c2af52d582c401 | mehdi902/pythonProject3 | /Client.py | 1,314 | 3.53125 | 4 | import sqlite3
conn = sqlite3.connect('base.db')
cursor = conn.cursor()
class Client():
def __init__(self,id,nom,prenom,adresse,numeroAgence):
self.__nom = nom
self.__prenom = prenom
self.__adresse = adresse
self.__numeroAgence = numeroAgence
self.__id = id
def get_id(s... |
3e9e3098b25a643f32972c27425cc829eece1cde | pedfalcao/Algoritmos | /quick.py | 668 | 3.84375 | 4 | def quicksort(array):
if(len(array) > 1):
pivo = 10
indice = 0
for i in range(len(array)-1):
if(array[i+1] < pivo):
indice += 1
aux = array[i+1]
array[i+1] = array[indice]
array[indice] = aux
print(array)
... |
89c95be051d1bb776641d36c3ec41c06ac9efa7e | xHoodies/TSP_GA | /genetic_algorithm.py | 8,318 | 3.90625 | 4 | import numpy as np
import random
import operator
import pandas as pd
import matplotlib.pyplot as plt
import time
"""
Gene: a city (represented as (x,y) coordinates)
Individual (aka "chromosome"): a single route going through all cities
Population: a collection of possible routes (i.e, collection of individuals)
Parent... |
a975fcf537ed2ba8eb21aefd8f323c9d440606fa | skshihab069/Data-Structure | /Linked list finnal.py | 3,644 | 4.03125 | 4 | class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def insert_at_beggining(self, data):
node = Node(data, self.head)
self.head = node
def append_items(self, data):
... |
ad09077a04553908dc4cfad1473ca2729ed3e812 | skshihab069/Data-Structure | /recursion.py | 1,412 | 4.09375 | 4 | # recursion is a method of solving problem by breaking it into smaller parts
# any problem that can be solved by iterative algorithms can be solved by recursion
# recursion is simply repeating a function until it reaches its base case
# a base case is a condition that stops the recursion
# recursion does a similar job ... |
18fe60392effe34c90912db5e10585a7ce66006f | skshihab069/Data-Structure | /binary search.py | 1,081 | 4.0625 | 4 | # Binary search is a searching technique for a sorted list
# it is much more efficient than linear search
# Binary search operates by searching through mid points of a list
# it checks if the mid point is the required search number
# if the mid is not the searched item it checks if the search number is greater than o... |
8aa1e84d00c6421d79ef6604915a712a791aa67f | barun511/datavis | /vis.py | 3,294 | 3.5 | 4 | import operator
from itertools import zip_longest
def clean_prison_data(prison_data_file_name,cleaned_prison_data_file_name):
with open(prison_data_file_name, 'r') as prisonfile,open(cleaned_prison_data_file_name,"w") as outfile:
outfile.write("state,year,people\n")
i = 0
list_of_lines = pri... |
7db291ab6c43bff6a9660626b310f0c101f43fcb | mriosfdez/Adivina_el_numero | /Guess the number.py | 670 | 3.859375 | 4 | import random
print("Hola, ¿cómo te llamas?")
name = input()
print("Bueno," + name + ", estoy pensando en un número del 1 al 20")
secretNumber = random.randint(1, 20)
for guessesTaken in range(1, 7):
print("¿Qué número es?")
guess = int(input())
if guess < secretNumber:
print("Más a... |
8083766e703f278a2f1d19090e66be5970748832 | sebastienliu/leetcode_puzzles | /35_search_insert_position.py | 844 | 4.09375 | 4 | class Solution:
def searchInsert(self, nums, target):
"""
Given a sorted list of distinct integers and a target value, return index if the target is
found. If not, return the index where it would be if it were inserted in order.
"""
# If the target number is greater than any ... |
9c463b30e3b37584af7e02d093b4a6692bb677fa | Volodimirich/PythonEjudjePrac | /InherAndDesc/UniSize.py | 726 | 3.609375 | 4 | #Написать декоратор класса sizer, который добавляет в него поле size, равное длине объекта, если у объекта есть длина,
#или модулю целочисленного представления объекта в противном случае (предполагается, что ошибок нет).
#Предоставить пользователю возможность произвольно менять это поле.
class Halp(object):
def __... |
b846e8a702ea7a9f5a23424ab9469e90f0b23c08 | Tomdieu/Searching-And-Sorting-In-Python | /SeachSort.py | 2,793 | 3.8125 | 4 | class Sort(object):
"""docstring for Sort"""
def __init__(self, array):
self.array=array
self.n=len(self.array)
@property
def bubble(self):#ca c'est le tri a bulle
for i in range(self.n):
for j in range(0,self.n-1-i):
if(self.array[j]>self.array[j+1]):
self.array[j+1],self.array[j]=self.array[j],s... |
e2a771accf0b35e530ab0de09d713d182959f02f | zhan2212/CSC384 | /A2/kenken_csp.py | 6,715 | 3.625 | 4 | '''
All models need to return a CSP object, and a list of lists of Variable objects
representing the board. The returned list of lists is used to access the
solution.
For example, after these three lines of code
csp, var_array = kenken_csp_model(board)
solver = BT(csp)
solver.bt_search(prop_FC... |
ba2d61cbf3144dc2e41c219359d138a1acb945b3 | ccjoywang/material | /student.py | 498 | 3.65625 | 4 | import datetime
from person import Person
class Student(Person):
def __init__(self, name, birthday, courses):
Person.__init__(self, name, birthday)
self.courses = courses
def get_courses(self):
return self.courses
def speak(self):
print("I'm so tired!")
# usage
peter = ... |
e92b50f3472bc98c7ca8de6f23c1d5265be70bb3 | lizhe960118/cs231n | /assignment3/cs231n/layer_basic.py | 12,808 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2018/10/23 16:23
@Author : LI Zhe
"""
import numpy as np
def affine_forward(x, w, b):
"""
computes a forward pass for a fully_connected network
:param x: input data (N,d_1,d_2,d_3), what we used in the partial is (N, 32, 32, 3)
:param w: w... |
a16549574b1355af216bb29a7be1a332c14f8297 | vendanner/program-language | /python/learn/python/ch10/module.py | 1,656 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
模块:
首次导入:
创建模块的命名空间
执行模块对应文件,产生的名字存放于模块文件所对应的命名空间
在当前执行文件中拿到模块名,该模块名指向模块文件所对应的命名空间
查找:
内存中已经加载的模块
内置模块
sys.path 路径中包含的模块
包:
一个特殊的模块;一个文件夹就是一个包;包内必须有初始文件 __init__.py
导入:
导入带点时,点的左边必须是一个包
包内模块... |
52f92ef61166cf70e7a3f5883be2cbb9944f4f5d | vendanner/program-language | /python/learn/python/ch04/strCode.py | 777 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
字符编码:
不同国家规定的编码就是一张表:unicode,UTF-8 都是通用格式与国家无关,但UTF-8 省空间
python3 默认展示是 unicode
unicode --> 编码encode --> GBK/UTF-8
GBK/UTF-8 --> 解码 decode --> unicode
"""
def gbk_utf():
"""
:return:
"""
x = "上"
print(x)
code_gbk = x.encode('gb... |
e83aa93bb97f02b9d6179155bc22090e525f348c | Tahmid-Hossain-287/Algorithm-Solution | /Diagonal Difference.py | 438 | 3.65625 | 4 | sample_input = [[11, 2, 4], [4, 5, 6], [10, 8, -12]]
def diagonalDifference(arr):
# Write your code here
first_diagonal = 0
second_diagonal = 0
first_pos = 0
second_pos = -1
for _ in arr:
first_diagonal += _[first_pos]
first_pos += 1
for _ in arr:
second_diagon... |
5c5ce94c08b3a40af2ac09a4b0c585046ff2711c | Sushmitaray/Code-Snippets | /Python/Chained function call.py | 142 | 3.875 | 4 |
def add(a, b):
return a + b
def subtract(a, b):
return a - b
a, b = 4, 5
print((subtract if a > b else add)(a, b)) # 9
|
c9d1f0d522ef0a01fd216a66279c25a8c4f8c499 | Mimickal/FunboxUsers | /add_user.py | 886 | 3.734375 | 4 | from random import choice
from string import ascii_letters, digits, printable
import scrypt
from sqlite3 import IntegrityError
import db
def randomStr(characters, length):
return ''.join(choice(characters) for _ in range(length))
def createUser(username):
temp_pass = randomStr(ascii_letters + digits, 12)
pw_salt... |
86fd16c03de3f6247fc4e8a8e348332099daa9f1 | ar600/Python-OOP | /multiples.py | 180 | 3.5 | 4 | # for count in range (1 , 1000):
# if (count%2 !=0):
# print count
# +++++++++++++++++++++++++++++++++
a = [1, 2, 5, 10, 255, 3]
print sum(a)
print sum(a)/len(a)
|
3e7ba12789e26859039280dcc350a2e129dca347 | ar600/Python-OOP | /animal.py | 1,313 | 4.03125 | 4 | class Animal(object):
def __init__(self, name, health):
self.name = name
self.health = health
def walk (self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def displayHealth(self):
print "Health is: ", self.health
a... |
419b6492fcf396d89435e50ffc969ae0782fcc9b | ar600/Python-OOP | /multiply.py | 182 | 3.921875 | 4 | a=[1,2,3]
arr = a
newArr=[]
def multiply():
# multiply by 5 function
for number in arr:
total=number*5
newArr.append(total)
print newArr
multiply() |
32329b726a3ba365956d859eca051f44c8da30a3 | jainsiddharth99/PythonBasics | /ifelifelse.py | 159 | 3.8125 | 4 | import time
today=time.strftime("%A")
if today=='Monday':
print('party')
elif today=='Wednesday':
print('howdy')
else:
print('waw-waw')
|
9c8dab5657de51149c7f0a07cab209b3929593cd | lancelote/princ_of_comp_1 | /week1/proj1.py | 821 | 3.890625 | 4 | """
Project 1: merge a line (part of 2048 game)
"""
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
new_line = slide(line)
for pos in range(0, len(line)):
if pos != len(new_line) - 1 and new_line[pos] == new_line[pos + 1]:
new_line[pos] *= 2
... |
763fbcfaa22330c29fa4f122981883bac046684b | concord-consortium/flow | /flow/blocks/timer.py | 1,014 | 3.71875 | 4 | from block import Block
# a basic timer block; turns on for a specified numbers of seconds then turns off for a specified number of seconds
class Timer(Block):
def __init__(self, block_spec):
super(Timer, self).__init__(block_spec)
self.counter = 0
self.decimal_places = 0
params =... |
5c3d23aa17693296be310aa279a8cc0c26c8cc93 | carlosberrio/holbertonschool-higher_level_programming-1 | /0x0B-python-input_output/9-add_item.py | 561 | 3.921875 | 4 | #!/usr/bin/python3
"""
Module for add_item method
Adds all arguments to a Python list, and then save them to a file
"""
import sys
import os.path
"""The os module provides methods for file processing"""
save_to_json_file = __import__('7-save_to_json_file').save_to_json_file
load_from_json_file = __import__('8-load_fro... |
ae485d7078b0a130d25f508fa3bbf2654b288fbd | carlosberrio/holbertonschool-higher_level_programming-1 | /0x0B-python-input_output/4-append_write.py | 312 | 4.34375 | 4 | #!/usr/bin/python3
"""Module for append_write method"""
def append_write(filename="", text=""):
"""appends a string <text> at the end of a text file (UTF8) <filename>
and returns the number of characters added:"""
with open(filename, 'a', encoding='utf-8') as file:
return file.write(text)
|
129c7dfb7e4704916d6a3c70c7b88de3f4ee5ab4 | carlosberrio/holbertonschool-higher_level_programming-1 | /0x07-python-test_driven_development/2-matrix_divided.py | 1,673 | 4.3125 | 4 | #!/usr/bin/python3
""" Module for matrix_divided method"""
def matrix_divided(matrix, div):
"""Divides all elements of a matrix by div
Args:
matrix: list of lists of numbers (int or float)
div: int or float to divide matrix by
Returns:
list: a new matrix list of lists
Raises:
... |
da59cabaff8a2d427caefe366ff1766d9d4f5cee | cheekujodhpur/fmm | /fmm/core/point.py | 645 | 3.671875 | 4 | """The class definition for our class
which controls all function of a n dimesnional point
"""
import numpy as np
class Point(object):
def __init__(self,vec=None):
#checks
if type(vec) != np.ndarray:
if vec==None:
vec = np.array([])
pass
else:
raise TypeError("Only ndarray allowed for point d... |
5f757306a85985ab1f8f71c26e308114ad83449b | pijingzhanji21/learning-of-python | /learning of python/file of space.py | 818 | 3.78125 | 4 | import os
def file_size(fname): #该函数传入一个fname
return os.stat(fname).st_size #返回该文件的大小
ll=[]
def file_list(path = None):
for root,dir,file in os.walk(path):
for f in file:
ll.append(os.path.join(root,f))
return ll #此句为file_list的测试语句
def total_size(path = None): #... |
5806f047a9c8281c7ce38433a35f9c84e2c8dfea | metajungle/gis-utils | /bounds_xy.py | 2,403 | 3.765625 | 4 | #!/usr/bin/python
"""
Finds the bounds of a given address using Google Geocoding API.
Outputs the bounds using the following pattern:
[upper-left x] [upper-left y] [lower-right x] [lower-right y]
where x = longitude and y = latitude
This is for example the format GDAL uses for specifying a bounding box.
"""
... |
efa68648706172970c196e8259a5e3ccbb6755e3 | meisterelijah/my-first-python-programs | /hello.py | 530 | 3.765625 | 4 | # This program says hello and greets a person by name.
#
# your name
# August 24, 2017
print("hello.")
print("what is your name?")
name = input()
print("it is good to meet you, " + name + ".")
name = input()
print ("Where were you born, Elijah?")
name = input ()
print ("Thats cool I would like to vist gr... |
9e21a3ee8a3f153241fbd9c27d8e5cb84bc01bda | hazemIII/Bionomial-coff-calculator-using-Python | /direct.py | 340 | 3.828125 | 4 | '''
Created on Nov 8, 2014
@author: hazem
'''
from math import factorial
n=input('enter n ')
k=input('enter K')
def BC_direct(n,k):
if k < 0 or k > n:
print('error')
return 0;
factn=factorial(n)
factK=factorial(k)
factm=factorial(n-k)
print('direct is')
print(factn/factK/factm)
... |
4f2d0ea723eac379d59ac68db1d20bee91e3d40b | lytarhan/Variance-Partitioning | /VP_Example.py | 2,149 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Leyla Tarhan
12/2020
Example showing how to call the variance partitioning functions using simulated data.
"""
# %% Dependencies
from Helpers import *
import numpy as np
import matplotlib.pyplot as plt
# %% simulate some data
# comparing 2 sets of variables, which each have 5 dimensions... |
5fc2cf32b3f3fbace16894c6b7b8b384539b4264 | KamalAres/Infytq | /Infytq/Day6/Assgn-44.py | 381 | 3.859375 | 4 | #PF-Assgn-44
def find_duplicates(list_of_numbers):
#start writing your code here
dub=[]
for i in list_of_numbers:
if list_of_numbers.count(i)>1 and i not in dub:
dub.append(i)
#dub=list(set(dub))
#dub.sort()
return dub
list_of_numbers=[1,2,2,3,3,3,4,4,4,4]
list_of_duplicate... |
ac98781df6169c661443e347c22760b6a88fad1c | KamalAres/Infytq | /Infytq/Day8/Assgn-55.py | 2,650 | 4.25 | 4 | #PF-Assgn-55
#Sample ticket list - ticket format: "flight_no:source:destination:ticket_no"
#Note: flight_no has the following format - "airline_name followed by three digit number
#Global variable
ticket_list=["AI567:MUM:LON:014","AI077:MUM:LON:056", "BA896:MUM:LON:067", "SI267:MUM:SIN:145","AI077:MUM:CAN:060","SI267... |
1c73ca075b6e0220084c2eb0b1d99530016c6c47 | KamalAres/Infytq | /Infytq/Day5/Assgn-34.py | 850 | 3.828125 | 4 | #PF-Assgn-34
def find_pairs_of_numbers(num_list,n):
#pass
#Remove pass and write your logic here
sum=0
count=0
num_list.sort()
#print(num_list)
for i in num_list:
for j in num_list:
#print(i,j)
if i==j:
#print("Hi")
continue
... |
3931dbe288e375b108e4a8fe90d47042efd86b8e | KamalAres/Infytq | /Infytq/Day1/Assignmnet-3.py | 529 | 3.5 | 4 | #PF-Assgn-3
#This verification is based on string match.
mileage=12
amount_per_litre=40
distance_one_way=190
per_head_cost=0
divisible_by_five=False
#Start writing your code from here
#Populate the variables: per_head_cost and divisible_by_five
distance_one_way=distance_one_way*2
total=distance_one_way/mileage
cost=t... |
966255090642a5d6619280e46d290641701871b5 | KamalAres/Infytq | /Infytq/Day8/Exer-41.py | 594 | 3.671875 | 4 | #PF-Exer-41
#This verification is based on string match.
def sum_all(function, data):
#pass #Remove pass and write the logic here
sum=0
for i in data:
if function(i):
sum+=i
return sum
list_of_nos= [100,200,300,500,1040]
greater =lambda x:x>10
divide = lambda x:x%10==0 and x<=... |
550dd3a2acd57c015d2cbba062efc232c8c6387a | shahisa/nltkTutorials | /stopWords.py | 352 | 3.953125 | 4 | from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
example_sentance = "This is an english showing of stop word filtration."
stop_words = set(stopwords.words("english"))
words = word_tokenize(example_sentance)
filteredSentence = []
for w in words:
if w not in stop_words:
filteredSentence.app... |
6981760443c7d33fc0825214ef03b69d0bd10365 | harishcoder-dev/python_pymera | /clock.pyw | 2,393 | 3.8125 | 4 | #!/usr/bin/python3.5
import turtle
import datetime
import time
def drawclock(radius,hours,minutes,length,color):
turtle.pensize(3)
turtle.penup()
turtle.goto(0,radius)
turtle.bgcolor("yellow")
turtle.pendown()
turtle.fillcolor(color)
turtle.pencolor("darkgray")
turtle.begin_fill()
f... |
87b6c3e96429b562fabaa0a713882614d332f00a | robertohernando/euler | /007/007.py | 691 | 3.984375 | 4 | #!python3
# -*- coding: utf-8 -*-
"""
10001st prime
-------------
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
"""
Utilizo la criba de Eratóstenes
"""
MAX = 500000 # Máximo número a tratar (arbitrario)
M = 10001
numeros... |
4610602490e0ec35ceed8d1e5d01a43d4e9a80c3 | amidying/python_chap_12_inheritance | /02_type_inherit.py | 777 | 4.03125 | 4 | # single inheritance
# multiple inheritance
# multilevel inheritance
# !1 single inheritance
# video 9:50Hours
class Employee:
company = "Google"
def __init__(self):
print("Hello dear boy")
def showDetails(self):
# print("This is an employee")
return "This is an employee"
class... |
3422999116f8ff1fa354aeab35a26d26923c0b93 | MBorgesT/FechamentoDeCaixa | /arquivos-caixa/relatorio/scripts/models.py | 1,148 | 3.5 | 4 | class Saida:
def __init__(self, idSaida, idFechamento, descricao, valor):
self.idSaida = idSaida
self.idFechamento = idFechamento
self.descricao = descricao
self.valor = valor
class FicaCaixa:
def __init__(self, idFicaCaixa, idFechamento, descricao, valor):
self.idFicaCaixa = idFicaCaixa
self.idFechamen... |
6b9a69cd44461457017bf58c3792c540b48538c3 | ditesh/project-euler | /6.py | 168 | 3.53125 | 4 | sum_of_squares = 0
sum = 0
for i in range(1,101):
print i
sum_of_squares += (i * i)
sum += i
print sum, sum_of_squares, sum*sum
print (sum*sum) - sum_of_squares
|
5a195c58bc440fce91c4a7ebc3a1f9eeb61d1ce1 | Wallabeee/PracticePython | /ex11.py | 706 | 4.21875 | 4 | # Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten,
# a prime number is a number that has no divisors.). You can (and should!) use your answer to Exercise 4 to help you.
# Take this opportunity to practice using functions, described below.
def isPrime(num):
... |
354194bd51375424cabef5afea448e4517296d37 | codingdojotulsadecember2019/instructor_phil | /_python/data_structures/data_structures.py | 1,152 | 3.9375 | 4 | class SLList(object):
def __init__(self):
self.head = None
def add_to_front(self, value):
new_node = SLNode(value)
new_node.next = self.head
self.head = new_node
return self
def print_node_values(self):
runner = self.head
while runner != None:
... |
71cd680918b49380d8337bef85bc0dca53f30e19 | mohmah7/osajana_kehitaminen-korkeakoulu | /harij08/L08T06.py | 183 | 3.953125 | 4 | first_number = input("Please insert year:")
second_number = first_number % 4
if second_number != 0:
print("It is not leap year.")
if second_number == 0:
print("It is leap year!") |
5e82ce137d7269b7f0cc1207402f762edd690e32 | mohmah7/osajana_kehitaminen-korkeakoulu | /harij07/harij0507.py | 441 | 3.546875 | 4 | balance = 2000.0
usr_input_third = 0.0
print("Bank account balance is",balance, "euros")
usr_input_first = input("How many euros will be added to the balane?")
usr_input_second = input("How many cents will be added to the balance?")
usr_input_second = usr_input_second+usr_input_third
usr_input_second = usr_input_second... |
4ebe5340f6327a20376da02d6c0d8586d93c527e | eliekawerk/Interview-Query | /Python.py | 15,833 | 3.921875 | 4 | #1. Sum to N -- Given a list of integers, find all combinations that equal the value N.
def sumton(integers,target):
dp = [[] for i in range(target+1)]
for c in integers:
for i in range(target+1):
if i<c: continue
if i==c:
dp[i].append([c])
... |
48827361a7a69c73104c32ec98bdddfe4e45cdc6 | kerimlisalman/GitHubKsao | /Ders2.py | 313 | 3.9375 | 4 | print('Как вас зовут?')
name = input() # считываем строку и кладём её в переменную name
print('Здравствуйте, ' + name + '!')
#
print ("birinci reqemi daxil edin ")
a=input()
print ("ikinci reqemi daxil edin ")
b=input()
c=a+b
print (a+" + "+b+" = "+c)
|
a68256be7cc5fcd232a645c72047f67ce6dcca1c | Petec0x0/ule_cbt | /ule_cbt_application.py | 68,418 | 3.546875 | 4 | __author__ = 'PETEC'
import os
from tkinter import *
from tkinter import messagebox
directory = os.getcwd()
environment = Tk()
environment.title(directory + "\ ule cbt application")
width = environment.winfo_screenwidth()
height = environment.winfo_screenheight()
environment.geometry("%dx%d+0+0" % (width, heig... |
cbfd2b42ccf3b61fa7442d70ebf4fd7bb929ac56 | macsteps/practice_python | /17_decode_web_page.py | 570 | 3.734375 | 4 | #!/usr/bin/env python
# goal: Use the BeautifulSoup and requests Python packages to print
# out a list of all the article titles on the New York Times homepage.
import requests
from bs4 import BeautifulSoup
url = 'http://www.nytimes.com/'
r = requests.get(url)
r_html = r.text
soup = BeautifulSoup(r_html, "html.parse... |
603b34aad224da5916edd751071772b1a4b5e8a6 | macsteps/practice_python | /18_cows_and_bulls.py | 1,441 | 3.859375 | 4 | #!/usr/bin/env python
# goal: generate random 4-digit number; user has to guess.
# number correct, in correct place = cow
# number correct, in wrong place = bull
from random import randint
counter = 0
def gen_number():
return randint(1000,9999)
def get_cows(answer, guess):
cows = []
# use list comprehen... |
93719972801a8ef1f292356cf209f7ec4a3ff7bd | macsteps/practice_python | /22_read_from_file.py | 1,050 | 3.5 | 4 | #!/usr/bin/env python
# goal: read from a file
if __name__=="__main__":
counter = 0
# ** read line by line **
#with open('nameslist.txt', 'r') as open_file:
#for line in open_file:
#print line.rstrip('\n')
#counter += 1
#print "Total -> ", counter
# ***************... |
2a44821644b80ba4f0acddad6bbb2a737ff33999 | jyyyyyyyy/target_offer_python | /两个链表的第一个公共结点.py | 861 | 3.609375 | 4 | #输入两个链表,找出它们的第一个公共结点。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
if not pHead1 and not pHead2:
return None
p1,p2 = pHead1,pHead2
length1 = l... |
aebdb295e0211b50f779468ec2f47971b832bb22 | jyyyyyyyy/target_offer_python | /左旋转字符串.py | 535 | 3.96875 | 4 | # 汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。
# 对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。
# 例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
# -*- coding:utf-8 -*-
class Solution:
def LeftRotateString(self, s, n):
left = s[:n]
right = s[n:]
return right + left
|
582439e9ab04f8dd22bd8da781121a7b68fa0358 | AntoRojo16/Ejercicio8Unidad2 | /claseConjunto.py | 2,149 | 3.828125 | 4 | class Conjunto:
__lista=[]
def __init__ (self):
self.__lista=[]
def agregar (self,unElemento):
self.__lista.append(unElemento)
def getElemento (self,i):
print(i)
return self.__lista[i]
def getConjunto (self):
cont=[]
for ele... |
0700980987b2eeba89d200d25892884c3894391f | Shubhibarve/Python-Projects | /guess the number.py | 615 | 4.03125 | 4 | import random
number=random.randint(1,10)
Player_name=input("Hello,What's your name?")
number_of_guesses=0
print('Okay! '+ Player_name+ ' I am Guessing a number between 1 and 10:')
while number_of_guesses < 5:
guess=int(input())
number_of_guesses +=1
if guess < number:
print('Your guess i... |
5ef7371e5477b760483d525e3701526176debfd5 | nisarg-goo7/Python6312 | /python/1Task6.py | 158 | 3.78125 | 4 | def fun(i):
if(i==1 or i==6 or i ==11)
print('+', '-'*4, '+', '-'*4, '+')
else:
print('/'' '*4,' '*4,'/')
for i in range(1,11);
fun(i)
i+=1 |
c565249554b9f07bcf3b5c79d607551ae97cc4fc | rene-d/edupython | /codes/pythagoricien.py | 570 | 4.15625 | 4 | # Recherche d'un triplet pythagoricien d'entiers consécutifs
# https://edupython.tuxfamily.org/sources/view.php?code=pythagoricien
# Créé par AgneS, le 17/06/2013 en Python 3.2
for i in range(100000): # On va tester avec la réciproque de Pythagore
# pour 3 nombres consécutif... |
96a82d5736c431df89401d7a5ff440f632c4b834 | rene-d/edupython | /codes/loto.py | 524 | 3.8125 | 4 | # Le jeu du nombre mystère
# https://edupython.tuxfamily.org/sources/view.php?code=loto
# Créé par AgneS, le 17/06/2013 en Python 3.2
from lycee import *
a=randint(1,100)
n=demande('Proposer une valeur')
if n!=a: # On teste si l'entier entre 1 et 100 choisi au hasard par la machine
# est différent du nomb... |
e7e4feeed5e1766aa2920354125300dca04d35c4 | rene-d/edupython | /codes/distance.py | 546 | 3.734375 | 4 | # Distance sur un axe gradué
# https://edupython.tuxfamily.org/sources/view.php?code=distance
# Créé par AgneS, le 17/06/2013 en Python 3.2
from lycee import *
# Ce programme donne la distance entre deux points distincts
# placés sur une droite graduée
xA=demande("Entrez l'abscisse du point A")
xB=demande("Entrez l'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.