blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f91cb838f47cdad4c906567f0045f02c9a6508ac | wxx17395/Leetcode | /python code/剑指offer/15. 二进制中1的个数.py | 1,657 | 3.96875 | 4 | """
请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。
示例 1:
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
示例 2:
输入:00000000000000000000000010000000
输出:1
解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
示例 3:
输入:11111111111111... |
702c63750204dd9e7fe4bf335c8b88470a211ff3 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/anbaopham/lesson08/circle.py | 1,865 | 4.09375 | 4 | import math
class Circle(object):
def __init__(self, radius):
self.radius = radius
#self.diameter = radius * 2.0
# @property
# def radius(self):
# return self.diameter / 2.0
# @radius.setter
# def radius(self, radius):
# self.diameter = radius * 2.0
@property
... |
7fac70d48618e248fe29ab0430826dd99cc32a79 | Ahmad-Magdy-Osman/AlgorithmsDataStructure | /Stack/mOsmanWeek4Ex.py | 4,185 | 4.0625 | 4 | #!/usr/bin/env python3
# encoding: UTF-8
############################################################################
#
# CS 160 - Week 4 Exercise
# Purpose: Stack ADT Practice & Extending Some Of The Textbook Functions
#
# Author: Ahmad M. Osman
# Date: February 25, 2017
#
# Filename: mOsmanWeek4Ex.py
#
#############... |
abe63ad3e498b0ce55d7152862c172a5dba78842 | asif-hanif/bayes_net_neural_density_estimator | /bayes_net.py | 6,792 | 3.5 | 4 | import numpy as np
class BayesNetwork():
def __init__(self, bn_structure):
'''
A class to create a Bayesian network
Input:
------------------------------------------
structure of Bayesian network should be given as dictionary.
keys of dictionary should be na... |
60a95b6ba35e4bc091a97c9f5ace9ef5f2b4132d | Tonykane923/BudkovQA24 | /ДЗ № 16 Задание 1.py | 751 | 3.984375 | 4 | list = []
num = input("Введите список чисел: ") # В ДЗ в этой строчке.split(',') Но так не рабоатет
for i in num:
if i != " ":
list.append(i)
def bubble_sort(list):
perestanovka_on = True
while perestanovka_on:
perestanovka_on = False
for i in range(len(list) - 1):
... |
a93ac26c413b766b662550b2de06f3a9cded0a60 | lmacionis/Exercises | /6. Fruitful_functions/Exercise_6.py | 1,218 | 4.28125 | 4 | """
Write a function days_in_month which takes the name of a month,
and returns the number of days in the month. Ignore leap years:
test(days_in_month("February") == 28)
test(days_in_month("December") == 31)
If the function is given invalid arguments, it should return None.
"""
import sys
def days_in_month(month_nam... |
4886906c44b21ee63be851f206d06f9a632a3eff | NickLc/Python | /Tipos de Datos/tipos_datos_simples.py | 646 | 4.03125 | 4 | #Tipos de datos en python
#Se puede pasar de un tipo a otro sin ningun problema
#cadenas
cadd = "cadena doble comilla"
cads = "cadena simple comilla"
cadm = """cadena multilineal
cadena1
cadena2
.
.
.
cadena n\n"""
#numero entero
ne = 10
#numero entero hexadecimal
neh = 0x23
#numero real
nr = 2.155
#Boolean(verda... |
c3343f3077a0add996e63891002560d66b4bac69 | ltzp/LeetCode | /DFS/回溯/LeetCode216_组合总和3.py | 1,161 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/9/13 0013 15:07
# @Author : Letao
# @Site :
# @File : LeetCode216_组合总和3.py
# @Software: PyCharm
# @desc :
class Solution(object):
def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[Li... |
456e3c27208093771b5ea3861dbdef7152f493d6 | Harshschoolwork/ICS2O0 | /Rough Work/Python Worksheets/Worksheet-III-answers/Worksheet-III-answers/wk-III-part-II-q6.py | 122 | 3.8125 | 4 | number = int(input("Choose a number between 0 and 20: "))
for i in range(0, int((number + 1)/ 2)):
print(i * 2 + 1)
|
89324bce64f108855a4a3f6530c2f0f911391aeb | dylanbram354/Data_Structures_Assignment | /linkedlist.py | 1,079 | 4 | 4 | from node import Node
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def append_node(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
self.tail = new_node
return
else:
... |
ceb8bd77f1429b65d93b795537eb722ed1c908a5 | aquaboom/PythonPrograms | /CapitalLetters.py | 419 | 4 | 4 | #Count no. of capital letters in a given file
import os
def Capfunc(): # Function definition to find the capital letters in a file
os.chdir("C:\\Users\\Sonali\\Desktop")
with.open('Filename.txt')as filename:
count=0
for element in filename.read():
if element.isup... |
67d30309e924c09c91f4b49b0c3a547a4c7b03bb | luispaiva40200280/ALG.E.Dados | /ficha n04 AED/ex09.py | 551 | 4.15625 | 4 | #substituir n decimas pelo seu respetivo nome
#para trabalhar o uso de funçao replace
texto=input("texto")
texto = texto.replace("0", "zero")
texto = texto.replace("1", "um") #só rersulta para
texto = texto.replace("2", "dois") #nº < que 10
texto = texto.replace("3", "três")
texto = texto... |
04004981f1d75904be625eaf54803d2ed94f8838 | jasmithadivya/pythonprograms | /2tuples.py | 62 | 3.515625 | 4 | num = int(input("enter a number of tuples"))
tuple= (1,2,3,4)
|
e428a9fc70ac7f00c4c0d1ae4f9b877a5d5229ca | enyapynot/python | /try-except.py | 288 | 3.84375 | 4 | try:
age = eval( input('Please enter your age: ') )
ten_years = age + 10
print ("In 10 years, you'll be", ten_years)
except NameError:
print ("You must enter a number for your age")
except SyntaxError:
print ("Now youu are just being silly")
print ("Have a nice day. Goodbye.")
|
f1223d209f4c942ae2eea89d22f0b86511ad3cdd | Kyle-dreamburner/Python-automate_boring_stuff | /chapter5字典和结构化数据/5.p1.py | 976 | 3.984375 | 4 | #-*-codeing:utf-8-*-
# 你在创建一个好玩的视频游戏。用于对玩家物品清单建模的数据结构是一个字
# 典。其中键是字符串,描述清单中的物品,值是一个整型值,说明玩家有多少该物
# 品。例如,字典值{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}意味着玩
# 家有 1 条绳索、 6 个火把、 42 枚金币等。
# 写一个名为 displayInventory()的函数,它接受任何可能的物品清单, 并显示如下:
# Inventory:
# 12 arrow
# 42 gold coin
# 1 rope
# 6 torch
# 1 d... |
ca64090b4b99d4eb3aa35774ee8b650fcd25e9c2 | FarinazMortaheb/Intro-to-Python-Course | /Day4_Abstraction/dataframe_to_binary.py | 1,521 | 3.59375 | 4 | """
dataframe_to_binary.py
Author: Nicholas A. Del Grosso
some functions that convert dataframes to a basic binary file format.
An example of What Not To Do (TM) and part of an explanation of "binary"
as a format in general.
"""
from typing import *
import struct
import pandas as pd
class BinaryFormatter(NamedTupl... |
0b8cac707c23ae97d36982c8e9c22901c0c711ba | eliahvo/pdf-merger | /PDFMerger.py | 2,700 | 3.625 | 4 | import tkinter as tk
import tkinter.filedialog as tkfileDialog
import PyPDF2
pdfFiles = []
outputFile = ""
# basic window
window = tk.Tk()
window.title("PDF Merger")
window.geometry("500x400")
window.minsize(500, 400)
# header text
heading = tk.Label(window, text='PDF Merger')
# heading.place(relx=0.3, rely=0.1, anc... |
856ae0a7c06e27047fd0188a64ae12c433a90ce7 | alvinps/face_swap | /main.py | 2,709 | 3.53125 | 4 | import tkinter as tk
from tkinter import filedialog
from PIL import Image
from PIL import ImageTk
def swap_function():
pho = Image.open('test1.jpg')
pho = pho.resize((250,250), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(pho)
l3_photo.configure(image= photo)
l3_photo.image = photo
def sour... |
c20f2bf421fbacb934bcdaa4196696cedc092bfe | szj22233060/leetcode | /数组中最长前缀.py | 1,009 | 3.6875 | 4 | # coding: utf-8
# @Time : 2018/9/28 9:46
# @Author : Milo
# @Email : 1612562704@qq.com
'''
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
输入: ["flower","flow","flight"]
输出: "fl"
'''
class Solution:
def longestCommonPrefix(self, strs):
#确定共同前缀最小值即循环次数
min_num = min([len (i) for i in strs])
... |
d76ee82604414e587539aa8cc8a9fe15e690f2a0 | lwtor/algorithm_learning | /4_二分查找/binary_search.py | 902 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 使用递归的方式
def binary_search(L, num):
return binary_search_inner(L, 0, len(L), num)
def binary_search_inner(L, start, end, num):
if start > end:
return -1
mid = (start + end) // 2
print(start, end, mid)
if L[mid] == num:
return mid
... |
111d604951fba4c805510f7943d7ff3749fa9b3c | AustinRCole/python-scripts-finance-elections | /PyBank/main.py | 2,082 | 3.609375 | 4 | import os
import csv
#read file
bank_csv = os.path.join('Resources', 'budget_data.csv')
with open(bank_csv,'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
#header
next(csvreader)
#convert csv columns to lists
period = []
profit_loss = []
for row in csvreader:
dates... |
9cd6f8579bfcafac9791c132e38373de0d6bd521 | CRAswinRaj/Software-Module-Abhiyaan-2021 | /SectionB/B3_1.py | 1,435 | 3.515625 | 4 | import cv2
# Reads the image
img = cv2.imread('Resources/abhiyaan_opencv_qn1.png')
# Reads the sample image, which is used to generate histogram
sample_img = cv2.imread('Resources/sample.png')
# Convert the images to hsv type
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
sample_hsv = cv2.cvtColor(sample_img, cv2.COL... |
fbd050bc5c0608e178710817df9ca0e7814f344a | HoangQuy266/nguyenhoangquy-fundamental-c4t4 | /Session02/btvn.turtle_shape2.py | 336 | 4.03125 | 4 | from turtle import *
speed (-1)
n=3
for i in range(n):
forward(100)
left(120)
color("red")
n1=4
for i in range(n1):
forward(100)
left (90)
color("blue")
n2=5
for i in range (n2):
forward(100)
left(72)
color("red")
n3=6
for i in range(n3):
forward(100)
left (... |
027035d5a73af34ce6f01e9622f94dc1bda4c79f | TheHumanCodeOrg/thesoundoflife | /python/polypeptide.py | 3,016 | 4.0625 | 4 | from amino_acid import *
from math import pi, cos, sin
from graphics import *
"""
Polypeptide stores a list of amino acids. Typical use involves calling addAmino with a sequence of amino
acids, until a stop codon is reached. Then, one can call getIntersections to get all of the indexes where
the polypeptide intersect... |
ac759539d7e9d1432cd5f0189ca1bc7e02c227ad | suhelm/pythonexamples | /calcemi.py | 269 | 3.65625 | 4 | import loancalculator
repayments1={}
loanamount=input('input a loan amount')
loaninterest=input('input a rate of interest')
term=input('input a term in month')
repayments1=loancalculator.loancal(int(loanamount),int(loaninterest),int(term))
print (repayments1)
|
02cc27ddfe1133bb0cb85f7b089bf7fc0b5047b6 | 0martinelli/pythonFirstSteps | /aula13d51.py | 239 | 3.75 | 4 | #programa que leia o primeiro termo e a razao de uma PA e mostre os dez primeiros termos dessa razao
t1 = int(input('Insira o primeiro termo da PA: '))
r = int(input('Insira a razao de PA: '))
for c in range(0,r*10,r):
print(t1+c)
|
6274388c564911f7561e63c8aa1709e0f35455f5 | lizhiquan/learning-python | /lab-8-movie-via-proxy-lizhiquan/movie_database_proxy.py | 5,524 | 3.5625 | 4 | """
This module houses the MovieDatabaseProxy class and its supporting
classes to control access to the database.
"""
import enum
import pandas
from movie_database import Movie, MovieDatabase
class UserAccessEnum(enum.Enum):
"""
Represents different access permissions.
"""
MEMBER = "member"
"""The... |
705c0e4d974d2cb14b2a53d20967c8f8eba0b8c7 | shaikhAbuzar/named-entity-recognition | /app.py | 2,871 | 3.65625 | 4 | import wikipediaapi
import spacy
import streamlit as st
import pandas as pd
import altair as alt
from spacy import displacy
from collections import Counter
import en_core_web_sm
# loading the english language for nlp
# nlp = spacy.load("en_core_web_sm")
nlp = en_core_web_sm.load()
# creating the wikipedia api object... |
c2190ebf7ba606364e140a07ea005bad6b2e019d | ashleefeng/qbb2017-answers | /day3-lunch/sort.py | 1,223 | 3.765625 | 4 | #!/usr/bin/env python
import random
nums = []
size = 50
for i in xrange(size):
r = random.randint(1, 100)
nums.append(r)
nums.sort()
# print nums
key = random.randint(1, 100)
print "Your key is %d" %key
found = False
print "Doing linear search"
for i in xrange(len(nums)):
v = nums[i]
if key ==... |
99f69756e066c38521579ab5a9da8d446dfaefff | oleksa-oleksa/Python | /Programming_Foundations_with_Python_ud036/mindstorm.py | 439 | 3.859375 | 4 | import turtle
def draw_square(turtle):
# Draw 4 sides of a square
for side in range(4):
turtle.forward(100)
turtle.right(90)
def draw_art():
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("yellow")
brad.speed(6)
... |
54abd103997148c3326c5bb612ea91244a6b5cee | MTGTsunami/LeetPython | /src/leetcode/string/451. Sort Characters By Frequency.py | 1,060 | 4.25 | 4 | """
Given a string, sort it in decreasing order based on the frequency of characters.
Example 1:
Input:
"tree"
Output:
"eert"
Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
Example 2:
Input:
"cccaaa"
Output:
"... |
9fa82f2a66ec918579f64bf9c67c620b02b9abd1 | Easterok/leetcode.problems | /three-sum-closest.py | 1,395 | 4 | 4 | # Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target.
# Return the sum of the three integers. You may assume that each input would have exactly one solution.
# Example 1:
# Input: nums = [-1,2,1,-4], target = 1
# Output: 2
# Explanation: The sum ... |
576f2c3dd29a40581c60778ae74e71901c1cf4e2 | CherryArun/Assignment-python-zero-to-Hero-D1 | /assignment_1.py | 97 | 3.875 | 4 | x=int(input("Enter 1 st input"))
y=int(input("Enter 2 nd input"))
print(x**y) # X to the power y
|
ab1957c7cf2b63f6a3cbf08d86122d76ea6e77d1 | lucasffgomes/Python-Intensivo | /seçao_04/exercicios_seçao_04/exercicio_02.py | 239 | 3.953125 | 4 | """
Faça um programa que leia um número real e o imprima
"""
print("Olá Lucas!")
numero = float(input("Digite um número com ponto: "))
print(numero)
print("Esse", numero, "possui ponto flutuante, por isso é considerado um FLOAT.")
|
7ecb997d3a03b1b4da024a68c9ad0039217a8c4f | shuang55/chopsticks-and-ss | /subtractsquaregame.py | 2,825 | 4 | 4 | """a subtractsquareGame module - a subclass of Game"""
from typing import Any
from game import Game
from subtractsquarestate import SubtractSquareState
class SubtractSquareGame(Game):
"""
A class to play subtractsquare - is a subclass of (extends) class Game
"""
def __init__(self, p1_turn: bool) -> N... |
b4086220b28ba7d4af263dbb3aca3b84f4741073 | Mahedi522/Python_basic | /22_Fibonacci_number.py | 196 | 3.78125 | 4 | first, second = 0, 1
for i in range(0, 51):
if i <= 1:
fibo = i
print(i)
else:
fibo = first+second
first = second
second = fibo
print(fibo)
|
c0753905c6d7c1b797956822b953c919e7bc64f4 | liugenghao/pythonstudy | /Thread/threading_ex1.py | 467 | 3.5625 | 4 |
import threading
import time
def run(n):
print('task:',n)
time.sleep(2)
starttime = time.time()
t_objs = []
for i in range(50):
t = threading.Thread(target=run,args=('t%s'%i,))
t.setDaemon(True)#把当前线程设置为守护线程,主线程无需等待守护线程结束,即可自行结束
t.start()
t_objs.append(t)
# t.join()
for t in t_objs:
t.join... |
887f545ff77e65df62e5273d35461f00393bad91 | Ayush05m/coding-pattern | /Python Codes/Max_sub_array_of_size_k.py | 497 | 3.96875 | 4 | def max_sub_array_of_size_k(k, arr):
max_sum = 0
window_sum = 0
for i in range(len(arr)-k +1 ):
window_sum = 0
for j in range(i, i + k ):
window_sum +=arr[j]
max_sum = max(max_sum, window_sum)
return max_sum
if __name__ == '__main__':
print("Maximum sum of a sub... |
78753e76260959ff27ac8f58ebeeede7781aa127 | mahyar-madarshahian/Project-Python | /Kashan-method1/method1_leaf_paths.py | 1,675 | 3.6875 | 4 | # در این ماژول، میان برگ های حاصل از درخت اشتاینر مسیرهای اولیه ایجاد می شود و در ادامه این مسیرها داخل الگوریتم ژنتیک گذاشته می شود.
import steiner_algorithm
import pandas as pd
import operator
from functools import reduce
reader_points =pd.read_excel(r'E:\learning_pymc3\Thesis_Code\Steiner_Algorithm\kashan\kashan_poi... |
e61a6ea032ad0bd30e10630acaace89fd965fa74 | mnuck/project-euler | /12/main.py | 357 | 3.796875 | 4 | #!/usr/bin/env python
def numFactors(n):
factors = 2
for i in xrange( 2, (n/2)+1 ):
if( n % i == 0 ):
factors += 1
return factors
i = 1
biggest_n = 0
triangle = i
while( True ):
i += 1
triangle += i
n = numFactors(triangle)
if( n > biggest_n ):
biggest_n = n
print tri... |
59b2b900aefea7c99daf060ae6c95b4eff77e77b | zhaoxy92/leetcode | /78_subsets.py | 326 | 3.921875 | 4 | def subsets(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
all_subsets = [[]]
if not nums:
return all_subsets
for num in nums:
for idx in range(len(all_subsets)):
all_subsets.append(all_subsets[idx] + [num])
return all_subsets
print(subsets([1,... |
8f736fa0bc2f7296f440c7a0d721dd6082fb9a1b | scheumann23/AI_Class_A1 | /part3/assign.py | 16,305 | 4.0625 | 4 | #!/usr/local/bin/python3
import numpy as np
import sys
import time
# Reads in the data from the external file and stores it in a list
def load_data(file_name):
data_list = []
with open(file_name, 'r') as file:
for line in file:
line = line.strip('\n')
data_list.append(list(line.... |
c7939d7e1aa999196a4dfe25effc5eb4bcdea797 | aliahmadcse/Learning_Python | /data_structures/lists.py | 152 | 3.609375 | 4 | letters = ['a', 'b', 'c']
zeros = [0]*5
combined = letters+zeros
print(combined)
number = list(range(0, 20))
chars = list('Python Course')
print(chars)
|
635967821ddf42dbf576df297c1f4228520737d7 | Bngzifei/PythonNotes | /学习路线/2.python进阶/day07/07-协程.py | 1,166 | 3.75 | 4 | """
还是单任务(单线程程序),只是在遇到阻塞(就是等待)的时候,切换任务去执行
协程:微线程/用户级别的多任务机制.<用户自己的程序实现的>
线程/进程:操作系统级别的多任务机制
使用场景:
多任务数量很大>几千的时候就使用协程 或者网络型的程序 优先考虑使用协程
挂起:就是在那个位置定住了不动,等到下一次开始的时候从这个位置继续开始执行.
"""
import time
def worker1():
"""生成器函数"""
while True:
print('in worker1')
yield
time.sleep(0.5)
def worker2():
while True:
pr... |
8f7f125d94e3dfba835c93a3f28087ecac3dc580 | PRKKILLER/Algorithm_Practice | /LeetCode/0622-Design Circular Queue/main.py | 2,869 | 4.3125 | 4 | """
Design your implementation of the circular queue.
The circular queue is a linear data structure in which the operations are performed based on FIFO
(First In First Out) principle and the last position is connected back to the first position
to make a circle. It is also called "Ring Buffer".
One of the benefits ... |
8659f30d84d7816ec4d0e6b5e4e8fcc0accead13 | maerli/python | /ga.py | 1,700 | 3.640625 | 4 | #exemplo para criar um pesquisador de nomes
import random
def getRandomChar():
return unichr(random.randint(32,126))
def getPhrase(tam):
txt = ""
for i in range(tam):
txt = txt + getRandomChar()
return txt
target = raw_input("Digite alvo:")
#criar populacao
tam_pop = 100
population = []
fitness = []
tam = len(... |
fbabe7e44fd3ad6cf2ceb268d8e3bdeab4d6d5ea | grantthomas/project_euler | /python/p_0024.py | 730 | 3.953125 | 4 | # Lexicographic permutations
# Problem 24
# A permutation is an ordered arrangement of objects.
# For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4.
# If all of the permutations are listed numerically or alphabetically, we call it lexicographic order.
# The lexicographic permutations of 0, 1 an... |
261d16178b5d8b08d5a9b1d891c30cadb4be803f | PhaniVaddadi/medium_data_structures_and_algorithms | /remove_duplicates_python.py | 1,712 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 17 15:16:04 2020
@author: sadrachpierre
"""
def remove_duplicates(items):
unique_items = set()
for item in items:
if item not in unique_items:
yield item
unique_items.add(item)
emails = ['rob@g... |
a2641026d5e1629fbd633c580eebca93aeeba397 | KristofferFJ/PE | /problems/unsolved_problems/test_332_spherical_triangles.py | 774 | 3.890625 | 4 | import unittest
"""
Spherical triangles
A spherical triangle is a figure formed on the surface of a sphere by three great circular arcs intersecting pairwise in three vertices.
Let C(r) be the sphere with the centre (0,0,0) and radius r.
Let Z(r) be the set of points on the surface of C(r) with integer coordinates.
L... |
70435f034e1682fe3e1910b8cd57827d78852d50 | charlotean/CS106A | /StoneMasonKarel.py | 1,373 | 3.640625 | 4 | from karel.stanfordkarel import *
"""
File: StoneMasonKarel.py
------------------------
When you finish writing code in this file, StoneMasonKarel should
solve the "repair the quad" problem from Assignment 1. You
should make sure that your program works for all of the
sample worlds supplied in the starter folder.
"""
... |
677c49d02d6805435c70d03a4b0236598d09cbbd | mmilett14/cracking-the-coding-interview | /chapter-1-arrays-and-strings/1.2-check-premutation.py | 1,257 | 4 | 4 | # Given two strings, write a method to decide if one is a permutation of the other.
def check_permutation(string0, string1):
letter_match = 0
if len(string0) != len(string1):
print("strings are different lengths - they are not permutations!")
else:
for i in range(0,len(string... |
bec5ff619fb6e6b943397dcd1f157db406f8be4b | enterlina/algorithm_bioinf | /HW2_Algoritms/venv/HW_Python.py | 1,504 | 3.625 | 4 | # class animals_taxonomy ( list):
animals = {'None': [ 'Chordata' ] , 'Chordata': [ 'Reptilia' , 'Aves' ] , 'Aves': [ 'Squamata' ]}
path = ''
# def add(animals , parent , child):
# self.animals[ parent ].append ( parent )
# self.animals[ child ] = child
# print (animals['Chordata'][0], animals['Chordata'][1... |
6103345b0af6139546735134de08b78cc32a88ba | DiamondGo/leetcode | /python/MoveZeroes.py | 1,759 | 4.0625 | 4 | '''
Created on 20151003
@author: Kenneth Tse
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
You must do thi... |
fa48d851aa50586ed31886bf2a214a794cd9126b | ramonvaleriano/python- | /Livros/Livro-Introdução à Programação-Python/Capitulo 5/Exemplos 5/Listagem5_6Melhorado.py | 281 | 3.828125 | 4 | # Program: Listagem5_6Melhorado.py
# Author: Ramon R. Valeriano
# Description:
# Developed: 28/03/2020 - 21:16
# Update:
end = int(input("Enter with number: "))
if end >= 1:
number = 1
while number<=end:
print(number)
number+=1
else:
print("What fuck is this!")
|
6074679a7bd9f3b199cdbd54173d1e86fa920854 | asadmujtaba/Python_Crash_Course_Eric_Matthes | /Chapter 11/11.1_11.2.py | 1,328 | 4 | 4 | #! python3
print("Task 11.1")
def city_country(city, country):
"""Return a tex like a Warsaw, Poland"""
return f"{city.title()}, {country.title()}"
import unittest
from city_functions import city_country
class CityTestCase(unittest.TestCase):
"""Test for program name 'city_country'"""
def test_city_... |
1ff1f6324e2e5ba6d222b0ca761ea829ee8a72c0 | burakates/Algorithms | /Course 4/floydwarshall.py | 2,995 | 3.828125 | 4 | '''floydwarshall.py: Dynamic Programming/Graph Theory'''
'''@author: Pranjal Verma'''
'''
-ve cycles:
For any i-j shortest path where i = j, the value has to be 0 (taking the empty path from
i to itself). If you start from i and go towards any other node != i (where i=j), in order
to come back to i you HAVE to tr... |
6a73b0abfedbdc2d084a904259765c6ecc385d7c | jkooy/Python-programming | /gather_values2.py | 2,367 | 4.21875 | 4 | def get_sample(nbits=3, prob=None, n=1):
'''
Given a number of bits, write the get_sample function
to return a list n of random samples from a finite probability mass
function defined by a dictionary with keys defined by a specified number of bits.
For example, given 3 bits, we have the following... |
f041c965537c46773d8aa178eb9838659abf6b17 | cwi-swat/Funcon4J | /performanceTests/fib.py | 228 | 3.75 | 4 | import time
def fib(n):
if n < 2:
return 1;
else:
return fib(n - 1) + fib(n - 2)
def loop(n):
for i in range(0, n + 1):
print(fib(30))
for i in range(10):
start = time.clock()
loop(100)
print(time.clock() - start) |
80d432be96e1edd48c0a51da51ebe72d56f79cee | pangyouzhen/data-structure | /unsolved/99 recoverTree.py | 744 | 3.578125 | 4 | # Definition for a binary tree node.
from base.tree.tree_node import TreeNode
# TODO
class Solution:
def recoverTree(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
self.ans = []
self.inorder(root)
for i in ... |
1b279c8e1b3652226638dd82e3b9b1f98bcd3acf | virgorasion/My-Python | /190411100064_M Nur Fauzan W[UAS].py | 1,458 | 3.796875 | 4 | class Node:
def __init__(self, init_data):
self.data = init_data
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self, newdata):
self.data = newdata
def setNext(self, new_next):
self.next = new_next
... |
68b93e801fcabadbd75a2273b8fb20f4c293af93 | burstfulcoderprograms/Calculator | /calcalator.py | 458 | 3.984375 | 4 |
def subtract(x, y):
results = x - y
return results
def add(t, y):
results = t + y
return results
def multiply(k, y):
results = k * y
return results
def divide(m, y):
results = m / y
return results
subtract_results = subtract(10, 20)
print(subtract_results)
add_results = add(5, ... |
08871a41644fccc049925617541933711fcafaa2 | remark997/DataRetrieval | /WordNet.py | 1,143 | 3.6875 | 4 | """ Find the 'synonyms', 'antonyms' of specific word using Wordnet
https://www.geeksforgeeks.org/get-synonymsantonyms-nltk-wordnet-python/
Import wordnet module
"""
from nltk.corpus import wordnet
import numpy as np
syns = wordnet.synsets("program")
print(syns[0].name())
print(syns[0].lemmas()[0].name())
coop_lis... |
00b40aefb76df2716fad6aa1a715700a1a02f7e6 | erin316/myfirstrepository | /second_chapter/exercise.py | 797 | 3.84375 | 4 | # class A:
# v = 100
# def __init__(self):
# self.v = 200
# a1 = A()
# a2 = A()
# del a2.v
# print(a1.__dict__)
# print(a2.__dict__)
# print(A.v)
# print(a2.v)
# print(a1.__class__.v)
# print(list((("aaa"))))
# d = {"a": 3, "b": 2, "c": 1}
# print(d.clear())
# class A:
# a = 1
# obj = A()
# obj.a = ... |
76b602802f1bdd461cfbe9c1560e4220d8026c97 | new-power-new-life/Leetcode-30-Days-Code-Challenge-April-2020 | /Week3/3 - Number of Islands/Solution.py | 777 | 3.546875 | 4 | #
# Created on Fri Apr 17 2020
#
# Title: Leetcode - Number of Islands
#
# Author: Vatsal Mistry
# Web: mistryvatsal.github.io
#
class Solution:
def bfs(self, grid, i, j):
if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[i]) or grid[i][j] == "0":
return None
grid[i... |
9dab90dc78a91d4a67399af496ca985bdeadc304 | tnakaicode/jburkardt-python | /graphics/lissajous_plot.py | 1,621 | 3.9375 | 4 | #! /usr/bin/env python3
#
def lissajous_plot ( ):
#*****************************************************************************80
#
## lissajous_plot draws a Lissajous curve.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 27 May 2016
#
# Author:
#
# John Burkardt... |
cc77a5c2a7cbeb9fcf2e31b3f73959d23ae78736 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4352/codes/1613_1801.py | 125 | 3.96875 | 4 | objeto = str(input("digite um objeto: "))
numero = int(input("digite um numero: "))
print(("Abra " + objeto + " ")* numero)
|
543cfbf6e9d9b08a60891105816198cc486f659c | sen48/SemanticCore | /bm_25/invdx.py | 22,950 | 3.734375 | 4 | """
Строит обратный индекс коллекции текстов и считает значение показателя релевантности документа запросу по формулам из
статьи «Алгоритм текстового ранжирования Яндекса» с РОМИП-2006. http://download.yandex.ru/company/03_yandex.pdf
"""
import math
import collections
import re
from string import punctuation
import p... |
36023fd8cb21cfc6c3e64f409b6eb9a44428fcdc | baharulIslamRocky/python-learning-workout | /URI/1004_Simple Product.py | 65 | 3.53125 | 4 | a=int(input())
b=int(input())
PROD=a*b
print("PROD = %d"%(a*b))
|
11156cc267f8797af9d708ac4f19ce3c8eb0aace | Hyseinov/Homework | /H.w.3.py | 608 | 3.859375 | 4 | import random
wordlist =['apple', 'watermelon', 'grapafruit', 'banana']
secret = random.choice(wordlist)
guesses = 'aeiou'
turns = 5
while turns > 0:
missed = 0
for letter in secret:
if letter in guesses:
print (letter,end=' ')
else:
print ('_',end=' ')
m... |
d93563938a67212cb1e2802d51687a64d6c76ec4 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4443/codes/1806_2544.py | 257 | 3.75 | 4 | from numpy import *
ve = array(eval(input("Digite o tamanho das batatas: ")))
vs = zeros(3, dtype=int)
for i in ve:
if(i >= 10):
vs[0] = vs[0]+1
elif(5 <= i < 10):
vs[1] = vs[1]+1
elif(i < 5):
vs[2] = vs[2] +1
print(vs[0])
print(vs[1])
print(vs[2]) |
8ee6d65e1f4f47c141c688376af9e4c47b61147e | sahilayank91/Stacked-Attention-Networks | /utils/get_image_features.py | 744 | 3.65625 | 4 | """
This function returns the image features for a given image.
The image is first resized to 224*224
The dimension of the extracted feature is (1, 14, 14, 512)
@Parameters
image : path to image
"""
from keras.applications.vgg19 import preprocess_input
from keras.preprocessing import image
from get_image_m... |
8b87668d9eb7c2a9bc72d2d91285eef25d1b3898 | zhouf1234/untitled3 | /函数编程函数28装饰器.py | 1,195 | 3.65625 | 4 | import time
#print(time.time()) #时间戳
#定义函数
#def get_dir_size():
#start_time = time.time()
#for i in range(1,100000):
#a = i * i
#end_time = time.time()
#print(end_time - start_time)
#get_dir_size()
#装饰器(decorator)就是闭包函数的一种应用场景
#定义装饰器
def run_time(func):
def wrapper():
func()
... |
1bb8a901d277167fc7665aa3640fceaa163804e6 | smohapatra1/scripting | /python/practice/start_again/2022/03212022/is_prime.py | 238 | 4.21875 | 4 | #Check if a number is prime : True/False
def is_prime(n):
for i in range(2,n):
if n %i == 0:
print (f"{n} is prime")
else:
print (f"{n} is not prime")
is_prime(int(input("Enter the number: ")))
|
e039e84369efa96ce81e22bfc5b3f0cf87b3a203 | dzieber/python-crash-course | /ch2/stripping_names.py | 334 | 3.703125 | 4 | # fun with stripping names
person_name = "\n\tAlabaster Jones the Third "
print("unmodified:" + " " + person_name)
print("lstrip:" + " " + person_name.lstrip())
print("rstrip:" + " " + person_name.rstrip())
print("strip:" + " " + person_name.strip())
# can we chain methods? Yes we can.
print("rstriplstrip:" + " " ... |
3fd30444c61c018c7c80d099a601a2105971847f | Melody713/Learn_Basic_Python | /Others/def.py | 290 | 3.84375 | 4 | #!/usr/bin/env python
# coding=utf-8
def count():
for i in range(1,10):
if i==5:
return
else:
print i
print "Hello World" #所以当i=5的时候就直接跳出了函数了,这里是不会被打印出来了!不是循环!!!
count()
|
fa0f2be3efa47cb2b2350bf50e73fd5afbe69d8c | murbar/code-challenges | /leetcode/factorial-trailing-zeros.py | 1,954 | 3.875 | 4 | # https://leetcode.com/problems/factorial-trailing-zeroes/
# had to look this up, wouldn't have come up with this formula on my own
'''
https://www.purplemath.com/modules/factzero.htm
5s pair with 2s from even factors to give us factors os 10.
Take the number that you've been given the factorial of.
Divide by 5; if... |
f8b76f674ba54930dff93b787940717a2dfb0c2e | fiona-young/PythonHackerRank | /Section1/EvenTree.py | 1,729 | 3.703125 | 4 | class Tree:
def __init__(self, root, adj_dict):
self.root = root
self.added = {root}
self.tree = self.depth_search(root, set(), adj_dict)
self.breaks = 0
def depth_search(self, current_node, added_set, adj_dict):
result = {current_node:{}}
added_set.add(current_n... |
1b89fa404400ff4de4f254e45aa5d205dc873cbe | evaneversaydie/My_Study_Note | /HW6/Dijkstra_06170128.py | 3,351 | 3.796875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
from collections import defaultdict
#Class to represent a graph
class Graph():
def __init__(self, vertices):
self.V = vertices #節點個數
# self.graph = []
self.graph_matrix = [[0 for column in range(vertices)]
for ro... |
ee0a1443cf405c9791ea64f56598b3372ba18011 | prototypemagic/proto-mastery | /codechef/steve/MAXCOUNT-shittyandbroken.py | 884 | 4 | 4 | #!/usr/bin/env python
# Steve Phillips / elimisteve
# 2012.02.01
num_tests = int(raw_input())
answers = []
for _ in range(num_tests):
len_next_line = int(raw_input()) # Not used
numbers = [int(x) for x in raw_input().split()]
maybe_answers = []
# For each test case, output two space separated integer... |
e640a2eea226e0cfd4b60bd63596c7fc8ed3084d | n0execution/Cracking-the-code-interview | /Linked_Lists/python/sum_lists.py | 1,344 | 3.75 | 4 | from LinkedList import LinkedList, Node
def generate_list(n, reverse=False):
result_list = LinkedList()
while n // 10 != 0 or n % 10 != 0:
remainder = n % 10
if reverse:
result_list.append(remainder)
else:
result_list.insert_at_index(0, remainder)
n ... |
edb48c8860141f90b51a0e2173f15bda2542e791 | tkessler45/GUI | /Tour/setcolor.py | 407 | 3.6875 | 4 | __author__ = 'tkessler'
from tkinter import *
from tkinter.colorchooser import askcolor
def setBgColor():
(colorvalues, hexcolor) = askcolor()
if hexcolor:
thebutton.config(fg=hexcolor)
print(hexcolor)
win = Tk()
thelabel = Label(win, text="This is the label")
thelabel.pack()
thebutton = Butt... |
2640a7c6d295a8a98aa8a1967341bbe16fac4c63 | silas-ss/aprendendo_python | /lista_exercicios_3_desafios/questao01.py | 350 | 4.0625 | 4 | #!/usr/bin/python
# coding: latin-1
def triangular(n):
for c in range(1,10):
if c*(c+1)*(c+2) == n:
return True
if (c+1) > 9 or (c+2) > 9:
return False
n = int(input("Digite um número: "))
if triangular(n):
print("%d é um número triangular!" %n)
else:
print("%d não é um n... |
75d47b07e7ad734799bf181df2255e7a6d1af878 | darthsuogles/phissenschaft | /algo/leetcode_537.py | 1,144 | 3.90625 | 4 | """ Complex number multiplication
"""
def complexNumberMultiply(a, b):
if not a: return b
if not b: return a
def parse_complex(s):
real, imag = None, None
sign, num = 1, None
for ch in s:
if '0' <= ch and ch <= '9':
num = num or 0
num... |
2ae2bf66d5d5ee53c574a7404ce752fe1ff39876 | lisasystaliuk/Python-GWC | /Python-Week-2/input.py | 120 | 3.515625 | 4 | answer = input("Who is your favorite author?\n")
print(answer + " is an awesome author! You have a very unique taste!")
|
8f316b65fab34c6370dd9971baeed194f420cb73 | shahhimtest/Algorithms | /Algorithms/Sorting/Bogo.py | 689 | 3.703125 | 4 | from random import shuffle
from time import sleep
from statistics import mean
n = list(range(10))
def bogosort(n):
iteration_counter = 0
while True:
shuffle(n)
if n == sorted(n):
#print(n)
print(f"sorted in {iteration_counter} steps")
return iteration_counte... |
991b0b2fbe6972ff66122b3ca767ac0a40b6e893 | gokulakannan19/PythonPrograms-Youtube | /Sum2Numbers.py | 696 | 4.21875 | 4 | # Hi In this tutorial I am going to show you how to add two numbers in Python
# first we want to get input from the user
# In order to get input we will use the input method
# we create two variables to store number1 and number2 respectively
# int method will change the string type to integer type
number1 = int(input... |
97b5aed58cfc6e85772541538fbdcf7609848230 | Abdulrauf-alhariri/Design_patterns | /template_pattern.py | 1,034 | 4.03125 | 4 | from abc import ABC, abstractmethod
# This method is used in case you're creating an application that has many tasks
# and they all have the same code but with small diffrencec so the template
# pattern is ideal instead of repeting the code
class AuditTrial(ABC):
def save(self):
print("Save")
... |
a18fcc152f717163d0e6a9a8fbb42842a2b3152a | flyingfr0g/Project | /Second Function/T_T_T.py | 4,635 | 4.375 | 4 | #!/usr/bin/env python3
# this is my re-creation of tic-tac-toe in python
# first we create the game spaces for the players to use. This will look very much like a number pad.
gameboard = {'7': ' ', '8': ' ', '9': ' ',
'4': ' ', '5': ' ', '6': ' ',
'1': ' ', '2': ' ', '3': ' '}
board_keys = [... |
3c59bbf2fc9fb731fb7ea374879127d7fe9ebfea | PulsatingGenius/extracting-primes-between-given-range- | /main.py | 366 | 3.5625 | 4 | import numpy as np
import math
def get_primes(n_min, n_max):
result = []
for x in range (max(n_min,2),n_max):
has_factor = False
for p in range(2, int(np.sqrt(x))+1):
if x % p ==0:
has_factor = True
break
if not has_factor:
result... |
7b202fbedabce8bafe5acc92516b8ee65d5f8fe4 | Vincentxjh/practice0813 | /005.py | 1,759 | 4.34375 | 4 | #第w五个练习 - 在派生类中调用基类的__init__()方法定义类属性
class Fruit:
def __init__(self, color = "绿色"):
Fruit.color = color
def harvest(self,color):
print("水果是:" + color + "的!")
print("水果已经收获......")
print("水果原来是:" + Fruit.color + "的!")
class Apple(Fruit):
color = "红色"
def __init_... |
c3f75b61e67750c061e186976e007002cd4e37a4 | swmarley/patch_tuesday_calculator | /patch_tuesday_calculator.py | 3,089 | 3.734375 | 4 | import calendar
from datetime import datetime, date, timedelta
def get_patch_tuesday(arg1, arg2):
cal = calendar.monthcalendar(arg1, arg2)
first_week = cal[0]
second_week = cal[1]
third_week = cal[2]
#Checks to see which week of the month the 2nd Tuesday falls on
if first_week[calendar... |
1c71d5afe98674faf45638458fdde12c66b748c9 | SkySwift/GB-Python-algorithms-and-data-structures | /Home Work 01/Task 07.py | 1,060 | 4.28125 | 4 | # По длинам трех отрезков, введенных пользователем,
# определить возможность существования треугольника, составленного из этих отрезков.
# Если такой треугольник существует, то определить,
# является ли он разносторонним, равнобедренным или равносторонним.
a = float(input("Введи сторону треугольника a: "))
b = float(i... |
b4190373aa0559c7c2657761e1e8d1712da56f34 | gnuton/RagBag | /Codility.org/part2/2-PermCheck.py | 244 | 3.609375 | 4 | # you can use print for debugging purposes, e.g.
# print "this is a debug message"
def solution(A):
M=len(set(A))
N=len(A)
if M != N:
return 0
# sum of 1+2+3+4+...+N
s=int(N/2.0*(N+1))
return int(sum(A) == s)
|
790bfe649f1cb93587878bb40d4c807fd95036b6 | mkirby42/Hash-Tables | /src/debug.py | 1,124 | 3.65625 | 4 | from dynamic_array import Dynamic_array
from hashtable import HashTable
def traverse(ht):
print('Traversial')
for i in ht.storage:
if i != None:
print(f'Node, {i}')
while i != None:
print(f"Linked Pair, Key: {i.key}, Value: {i.value}")
i = i.next
... |
39d1d8abb27b637657c6f741096bd63fd791d148 | jrgantunes/Hello-World | /classes_IP/toCheck.py | 1,918 | 4.40625 | 4 | #It will be used for the Birthday
import datetime
# Class use uppercase, object lowercase (Best Practices)
class Person:
#The attribute "birthday" has a default (if we do not provide a value when we start the object)
#The __init__ is used whenever an object of the class is constructed
def __init__(s... |
12ec85b1d89f1297d1490cb5a0813a24db49e435 | draft-land/osxphotos | /osxphotos/path_utils.py | 2,767 | 3.734375 | 4 | """ utility functions for validating/sanitizing path components """
import pathvalidate
from ._constants import MAX_DIRNAME_LEN, MAX_FILENAME_LEN
def sanitize_filepath(filepath):
"""sanitize a filepath"""
return pathvalidate.sanitize_filepath(filepath, platform="macos")
def is_valid_filepath(filepath):
... |
1bab5e986284bc659d45700ba57044e7313238ce | NicGiannone/week3-review-part2-NicGiannone-master | /caesar-encrypter.py | 988 | 3.75 | 4 | FileName = input("Enter the File to encrypt: ")
key = int( input("Enter the shift key: " ))
outputFileName = input("Enter the output file name: " )
Inputfile = open(FileName,'r')
OutputFile = open(outputFileName,'w')
alphabet = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
shiftedAlphabetStart = alphabet[len(... |
57ab16ff29f0b10af38aeaddfeedd160426296db | ceyhunsahin/TRAINING | /EXAMPLES/EDABIT/EXPERT/001_100/69_sum_and_product.py | 1,615 | 4.15625 | 4 | """
Sum and Product
Write a function that takes in two floating-point numbers s and p and returns a tuple of two floating-point numbers (x, y), where x + y = s and x * y = p. Round x and y to three decimal places.
If there are multiple solutions, return the solution with the lesser x (or lesser y, if the x values are ... |
1f9dee70642b72ae50524584fb282288a0e6c551 | khanjason/leetcode | /637.py | 1,199 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def LevelOrder(self,root,li):
h = self.height(root)
for i in range(1, h+1):
... |
09e9b2878859c2630ef58adb00b61069dececcf5 | zhlinh/leetcode | /0117.Populating Next Right Pointers in Each Node II/solution.py | 1,677 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-09
Last_modify: 2016-03-09
******************************************
'''
'''
Follow up for problem "Populating Next Rig... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.