blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
7a5c8b5a95127944ea4364fc0ea35b6376eda6ec | Luiti/etl_utils | /etl_utils/itertools_utils.py | 2,010 | 3.5 | 4 | # -*- coding: utf-8 -*-
from .design_pattern import singleton
@singleton()
class ItertoolsUtilsClass(object):
def split_seqs_by_size(self, seqs1, size1, inspect=False):
"""
Combinations of split seqs by special size.
Breadth-first version, see examples at bottom.
Thanks @fuchao... |
1aa4ab328870d608ae4f67526ef7802ff7e0a59f | ShivaniAgarwal21/Python | /Conditionals and Booleans.py | 3,273 | 4.65625 | 5 | if True:
print('condition was true') # condition was true
if False:
print('condition was true') #Nothing happens .. it says PATH: command not found
#Comparisions:
#Equal: ==
#Not Equal !=
#Greater Than >
#Less Than <
#Greater or Equal >=
#Less or Equal <=
#Object Identity is
#Boolean operations:... |
9c0a343267722249bd81eb7a55760c9540c5c92f | fengzige1993/PythonData | /com/python/unittest_test1/test_search.py | 3,480 | 4.0625 | 4 | """
test_search 模块里有两个类 :TestSearch1 & TestSearch2
"""
import unittest
class Search:
#被测试方法
def search_func(self):
print("search")
return True
#继承unittest里的TestCase类
class TestSearch1(unittest.TestCase):
#在测试类TestSearch调用之前,定义一个 (加@classmethod装饰器)类方法:setUpClass,传参(cls)
@classmethod
... |
10eed68a00ae77681de10bff09f8ebf45efd87dd | adrianbeloqui/Python | /alphabet_rangoli.py | 1,287 | 3.53125 | 4 | LETTERS = ['a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'x', 'y', 'z'
]
def print_rangoli(size):
printed = list()
width = ((size * 2) - 1) + (size - 1) * 2
for i in range(size - 1, -1, -... |
f88cb973550b169862745505c1dcc537eda2058e | ivankahnybediuk/python_12 | /homework.py | 6,989 | 4.03125 | 4 | import math
"""
Task 1
Method overloading.
Create a base class named Animal with a method called talk and then create two subclasses: Dog and Cat, and make their
own implementation of the method talk be different. For instance, Dog’s can be to print ‘woof woof’, while Cat’s can be
to print ‘meow’.
Also, create a simpl... |
8ef04c052caafdf1cfd966b7e69106b43cf07ca1 | Pranay2309/Test2_Corrections | /Question_29.py | 45 | 3.546875 | 4 | a=[0,1,2,3]
for a[-1] in a:
print(a[-1])
|
438b9d731e3a8ed1616b781d9f209d3a2841d98b | undergrowthlinear/learn_python | /test/practice/firstthirdpackage/content/mock_person.py | 282 | 3.734375 | 4 | # encoding=utf-8
class Person(object):
def __init__(self, name, age) -> None:
self.name = name
self.age = age
def __str__(self) -> str:
return super().__str__() + "\t" + self.name + "\t" + str(self.age)
person = Person('under', 18)
print(person)
|
e4821e2a3314c5da564404d8b52bf12529f54873 | wasi0013/Python-CodeBase | /ACM-Solution/SHAKTI.py | 89 | 3.6875 | 4 | for i in [0]*int(input()):print("Sorry Shaktiman" if int(input())%2 else "Thankyou Shaktiman")
|
a8095814987564b0d127c641b104c442cf99a899 | 1715974253/learned-codes | /28列表推导式.py | 233 | 4.03125 | 4 | # while循环
list1 = []
i = 0
while i < 10:
list1.append(i)
i += 1
print(list1)
# for循环
list2 = []
for j in range(0, 10):
list2.append(j)
print(list2)
# 列表推导式
list3 = [k for k in range(0, 10)]
print(list3)
|
d17c0e5c05816885cfb70c0ba81ca7e819a2d828 | ziuLGAP/2021.1-IBMEC | /exercicio3_20.py | 326 | 3.6875 | 4 | """
Exercicio 3-20
Luiz Guilherme de Andrade Pires
Engenharia de Computação
Matrícula: 202102623758
"""
def determina_primo(valor):
for num in range(2, valor + 1):
if valor == 2:
print(True)
elif valor % num == 0:
print(False)
print(True)
... |
75d9efa0cea5169a63ca374bedf73b982d64681e | aquatiger/LaunchCode | /class point.py | 1,101 | 4.15625 | 4 | import math
class Point:
""" Point class for representing and manipulating x,y coordinates. """
def __init__(self, initX, initY):
""" Create a new point at the given coordinates. """
self.x = initX
self.y = initY
def getX(self):
return self.x
def getY(self):
r... |
fdf6b4824cacca6e660fac184eff1fd67631619c | ccoo/Multiprocessing-and-Multithreading | /Multi-processing and Multi-threading in Python/Multi-threading/Locks and Sync Blocking/wait_blocking.py | 1,228 | 3.703125 | 4 | #!usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test module to implement wait blocking to address race condition, using
threading.Condition and threading.Event.
"""
__author__ = 'Ziang Lu'
import time
from threading import Condition, Event, Thread, current_thread
# Condition
product = None # 商品
condition = Cond... |
260b3fe8dcd748de23b8bcbc72c1e10d49a2042b | changsman/changs | /practice/sort.py | 636 | 3.546875 | 4 | a=[1,10,2,6]
a.sort() ##오름차순 정렬
print(a)
a.sort(reverse=True) ##내림차순
print(a)
b=1423434 ###숫자를 문자열로 반환하여, 배열로 변환(str, list)
print(list(str(b))) ##해당 숫자를 배열로 변환
c= list(str(b))
print(c)
c.sort(reverse=True) #내림차순 하기(sort로 오름차순 정렬 후, reverse로 내림차순)
print(c)
d="".join(c) #join으로 배열합치기
print(d)
#e=d(reverse=True)
... |
2570ba4dfd2120ef14ebb56df60c035dd9053e50 | hermespara/internship1 | /check_for_RNA.py | 526 | 3.53125 | 4 | #!/usr/bin/python3.6
import csv
all_data_path = "/home/hermesparaqindes/Bureau/internship1/complete.txt"
all_data = open(all_data_path, "r")
all_data_csv = csv.reader(all_data, delimiter='\t')
for row in all_data_csv:
analysis = row[4]
blood = row[2]
if ' RNA' in analysis and 'lymphocytes' in row[3] or ' ... |
b18b2c8ad2353293a222726d7070ff9e0f8919ec | key70/mlTest | /lambdaTest.py | 286 | 3.765625 | 4 | # def add(a,b):
# r = a + b
# return r
#연습)위의 함수를 람다식으로 만들어 봅니다.
add = lambda a,b: a+b
print(add(5,7))
# def max(a,b):
# r = a
# if b > r:
# r = b
# return r
# max = lambda a,b : a if a>b else b
#
# print(max(5,30)) |
e3f0e32a1a40862af5e0e66eb205a164db7f7626 | vsriram1987/python-training | /src/setsorter.py | 988 | 4.0625 | 4 | '''
Created on 06-Jan-2019
@author: vsrir
'''
import string
from _sre import ascii_tolower
def checkalph(stringval):
varset = ""
#list will convert set to list
#set will take unique values in map
#map has a lambda to convert all characters to lower case
#the list passed to the map is a ... |
77ebc84432d0bc8f911562e79a80d50b43fea7c2 | pranavkvc/Hand-Cricket-Game | /Handcricket/Handcricket.py | 19,072 | 4.125 | 4 | import time,random
user_score=0
computer_score=0
overs=0
balls=1
user_duck=True
computer_duck=True
user_out=False
computer_out=False
toss=['1','2']
bat_or_bowl=["Bat","Bowl"]
print("Toss time!")
choice=input("Head/Tails?\n1.Heads\n2.Tails\nEnter your choice: ")
if choice=='1' or choice=='2':
who=random... |
5ed1168c6daa809a0d2e8373f1dab54ae662f419 | Brunorodrigoss/pytest_structure | /tests/test_math.py | 2,107 | 3.96875 | 4 | import pytest
"""
This module contains basic unit tests for math operations.
Their purpose is to show how to use the pytest framework by example.
"""
# ------------------------------------------------------------------------
# A most basic test funcion
# --------------------------------------------------------------... |
692d6a97de0ca6363085c0466c2338aceee9c3b4 | FVerg/Simple-Python-Exercises | /04_Math_Operators/04_MathOperators.py | 968 | 4.625 | 5 | # In this lecture, we'll cover the usage of math operators
# First of all, let's see how some different operators used together work
result = 20-10/5*3**2
print (result)
# Python will execute the operations in this order:
# 1. Exponential (**): 2**3 equals to 2^3 = 2*2*2 = 8
# 2. Division and multiplication (On the ... |
75c07465135f9f00dd04c6d6aec444e709318e3a | huangyingw/submissions | /288/288.unique-word-abbreviation.233520184.Accepted.leetcode.py | 612 | 3.59375 | 4 | from collections import defaultdict
class ValidWordAbbr(object):
def __init__(self, dictionary):
self.dictionary = set(dictionary)
self.freq = defaultdict(int)
for word in self.dictionary:
self.freq[self.abbreviate(word)] += 1
def isUnique(self, word):
abbr = self.... |
c2257328d46536e5f51db962e03b97e82c1fd89c | RaguTeja/LinkedList-in-python | /LL.py | 4,576 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 18:43:35 2021
@author: dell
"""
class Node:
def __init__(self,data,next):
self.data=data
self.next=next
class LinkedList:
def __init__(self):
self.head=None
def length_ll(self):
count... |
db71670a929003b93ba7330682847cf65a7280f2 | gabriellaec/desoft-analise-exercicios | /backup/user_005/ch128_2020_04_01_16_44_34_377244.py | 332 | 3.828125 | 4 | x = input('Está se movendo?:')
if x == 's':
y = input('Deveria se mover?:')
if y == 'n':
print ('Silver tape')
if y == 's':
print ('Sem problemas!')
if x == 'n':
w = input ('Deveria estar parado?:')
if w == 'n':
print ('WD-40')
if w == 's':
print ('Sem problemas!'... |
f783eb67fce72502d836672bf4d9d9c8c8b8568d | shuowenwei/LeetCodePython | /Easy/LC896MonotonicArray.py | 999 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
@author: Wei, Shuowen
https://leetcode.com/problems/monotonic-array/
"""
class Solution(object):
def isMonotonic(self, A):
"""
:type A: List[int]
:rtype: bool
"""
increasing = True
decreasing = True
for i in range(len(A)-1):
... |
4376d952d29de5a0c2388eb8bd50a98b5613431f | manimanis/LeetCode | /May2021/sol_06.py | 1,674 | 3.859375 | 4 | """Convert Sorted List to Binary Search Tree.
https://leetcode.com/explore/challenge/card/may-leetcoding-challenge-2021/598/week-1-may-1st-may-7th/3733/
"""
from common.nodelist import TreeNode, ListNode
from common.testcases import make_tests
test_cases = [
(([-10, -3, 0, 5, 9],), [0, -3, 9, -10, None, 5]),
... |
e69bca8b1c4602a265bf41d13af8bbb8a320604f | Carina6/algorithms | /common_algorithms/move_left_m.py | 504 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-03-28 21:41
# @Author : hlliu
from random import choice
# 左移m位
def move(arr, m):
n = len(arr)
m = m % n
return arr[m:]+arr[:m]
def rand(arr, n):
res = []
for i in range(n):
index = choice(range(len(arr) - i))
res.ap... |
f33cca90ce99a1a47530eea8edff37c7733853cf | JonasSatkauskas/codewars | /list_filtering.py | 379 | 4.1875 | 4 | '''In this kata you will create a function
that takes a list of non-negative integers and strings
and returns a new list with the strings filtered out.'''
def filter_list(l):
final_list = []
for element in l:
if type(element)==int:
final_list.append(element)
else:
pass
return... |
7715b2009385ca0002b5d859adda39453b311f4a | Amandapoor/cmpt120poor | /IntroProgramming-Labs/evens.py | 155 | 4.125 | 4 | # a simple loop
# a program that prints out all the even integers from 2 through 20
def main():
for i in range(2, 21, 2):
print(i)
main()
|
e8f121bb85df42d7b71c5e277dbcf344256296e4 | adithirgis/DeepLearningFromFirstPrinciples | /Chap1-LogisticRegressionAsNeuralNetwork/DLfunctions1.py | 2,980 | 3.90625 | 4 | # -*- coding: utf-8 -*-
##############################################################################################
#
# Created by: Tinniam V Ganesh
# Date : 4 Jan 2018
# File: DLfunctions1.py
#
##############################################################################################
import numpy as np
import ... |
478f9b8fc9e7f088f35c1d0b1fb45fb6ae90889b | cankutergen/Other | /totalFruit.py | 851 | 3.546875 | 4 | class Solution:
def totalFruit(self, tree: List[int]) -> int:
if tree is None or len(tree) is 0:
return 0
last_fruit = -1
second_last_fruit = -1
last_fruit_count = 0
current_max = 0
global_max = 0
for fruit in tree:
... |
8eb29d6de6bd1ae276c566b99a22073d7094bbba | jsweeney3937/PRG105 | /Nested_If_Statements.py | 1,464 | 3.96875 | 4 | # Sweeney
# Assignment: Mobile Service Provider
userPackage = input("What package do you use, package A,B, or C? ").upper()
minutesUsed = int(input("How many minutes did you use? "))
price = float
if userPackage == "A" and minutesUsed <= 450:
price = 39.99
print("With package", userPackage, "and ", m... |
2050592709109f1bb341ce56c1c503632998c983 | LucasReboucas/lancamento_dados_simulacao | /simulacao.py | 3,335 | 3.65625 | 4 | ########################################################################################################
# Este arquivo simula "LANCAMENTOS" lancamentos de "DADOS" dados com "LADOS" lados e mostra a frequência dos possiveis resultados obtidos
# Autor: Lucas Rebouças
#####################################################... |
a2f16117572a14c3e60f07dd950b019c1a963ab6 | juliazhu09/Intro2Python | /Intro2Python.py | 21,498 | 4.46875 | 4 | # =================================
# === Python Programming Basics ===
# === Xiaojuan Zhu ===
# === xzhu8@utk.edu ===
# =================================
# ---HOW TO PREPARE YOUR COMPUTER---
# FOR THIS WORKSHOP
#
# ---STEP 1. INSTALLING SPYDER ---
# What is Spyd... |
186aacf4b7dd4a00680643f04a7a86692fda9d87 | mpettersson/PythonReview | /questions/data_structure/hash_map_list.py | 717 | 3.65625 | 4 | class HashMapList:
def __init__(self):
self.map = {}
def put_item(self, key, item):
if not key in self.map:
self.map[key] = []
self.map[key].append(item)
def put_list(self, key, list):
self.map[key] = list
def get(self, key):
if key in self.map.keys... |
d98cd7cf15f48c3f619ab85e9b69898f719f1004 | mjrish96/AirHockey | /gameObjects.py | 2,422 | 3.75 | 4 | import pygame
import math
class Paddle():
def __init__(self, x, y, radius, velocity):
self.x = x
self.y = y
self.radius = radius
self.velocity = velocity
def checkTopBottomBounds(self, height):
# top
if self.y - self.radius <= 0:
self.y = self.radiu... |
cbae4e8b17710d5622045f97fc244fb856b43ef2 | colbychang/othelloAI | /othelloRunner copy.py | 823 | 3.78125 | 4 | ## Othello Runner
from graphics import *
def initPieces(win):
loc1 = [3,3]
loc2 = [4,4]
loc3 = [3,4]
loc4 = [4,3]
whitePiece1 = Piece("white", loc1, win)
whitePiece2 = Piece("white", loc2, win)
blackPiece1 = Piece("black", loc3, win)
blackPiece2 = Piece("black", loc4, win)
blackPi... |
2ea6ce183752747b81b435b117235a9297f76c3e | Infosharmasahil/python-programming | /unit-3/function_args.py | 122 | 3.609375 | 4 | def add(*args):
total = 0
for item in args:
total += item
return total
print(add(1, 2, 3, 4, 5))
|
545d67b901880ad93402fe3376f2b1ac38087606 | Sjaiswal1911/PS1 | /python/Phonebook/proto1.py | 2,059 | 3.59375 | 4 | import pymysql
class Phonebook(object):
# Open database connection
db = pymysql.connect("localhost","root","J@imatadi19","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
contact_count = 0
def __init(self):
# Create table as per requirement
sql =... |
1e484dc3632384dfbe06cb27ff5e68aa4e76c981 | nauman-sakharkar/Python-3.x | /Data Structure & Artificial Intelligence/Linear_Sets.py | 952 | 3.875 | 4 | print("---------------------------------\nName : Nauman\nRoll No. : 648\n---------------------------------")
class Linear_Sets:
def __init__(self):
self.l=[]
def insert(self,e):
if e not in self.l:
self.l.append(e)
def union(self,b):
u=self.l[:]
for i in b.l... |
57b5b737ab89eb7cac97613ee2d99c0b5cdbe6be | VictrixHominum/primary_school_arithmetic_arranger | /arithmetic_arranger.py | 3,411 | 3.578125 | 4 |
def arithmetic_arranger(problems, answer=False):
arranged_problems = ""
tab = " "
if len(problems) > 5:
return "Error: Too many problems."
for i in range(len(problems)):
dashes = ""
problems[i] = problems[i].split()
try:
problems[i][0] = int(problems[i]... |
808eef113b3285ea36a971647f6510f766406102 | 369geofreeman/MITx_6.00.1x | /algos/search/BFS.py | 1,392 | 4.3125 | 4 | # BFS (Breadth First Search)
# Breadth First Search Implementation in Python,
# Finding shortest distance and path of any node from source node in a Graph.
# (B)--(A) (E)---(G)
# | | / | |
# | | / | |
# (C) (D)/--(F)---(H)
from queue import Queue
adj_lst = {
"A": ["B","D"],
"B": ["A"... |
9aa42cc24649b875d611a054530f52b09bc88176 | JohnlLiu/Sudoku_solver | /main.py | 1,432 | 3.671875 | 4 |
#Sudoku board
board = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
def solve(board):
#check if index is empty
indx = is_empty(... |
1549de1e28cac2201feb48b20e471789eaa881dc | Irondev25/plab | /9a.py | 919 | 4.21875 | 4 | import sqlite3
import os
if(os.path.exists("test.db")):
os.system("rm test.db")
connection = sqlite3.connect("test.db")
cursor = connection.cursor()
def createStudentDatabase():
statement = """
create table student(
usn varchar(10) primary key,
name varchar(50),
age integer,
address varch... |
b960ac54c57ae7299cd3a103da2e235cf457bf4c | sebastian-holguin/hw4 | /markov_chain.py | 663 | 3.625 | 4 | import numpy as np
# creating base numbers
def markov_chains(n1, N1):
n = n1
N = N1
# Creating the first array that'll hold numbers n x n
P = np.random.rand(n, n)
# Creating the second array that'll hold the initial state.
p = np.random.rand(n)
# .sum makes sure that the sum of the entrie... |
f6043a4761c5b9f4a0e0198c324fa5a1df52122b | ITZALMALTZURA/sum_primes.py | /sum_primes.py | 2,883 | 3.90625 | 4 | #! / usr / bin / python
# Archivo: sum_primes.py
# Autor: VItalii Vanovschi
# Desc: Este programa demuestra cálculos paralelos con el módulo pp
# Calcula la suma de números primos debajo de un entero dado en paralelo
# Software Python paralelo: http : //www.parallelpython.com
import math, sys, time
import pp
def ispr... |
11f3d7d6e3d6be343f1f01cb2025b887e949ed46 | ryankc/python | /yes_no.py | 295 | 4.28125 | 4 | print"Yes Means No And No Means Yes"
name = raw_input("What is your name?")
h = raw_input("1.Do you like your house? a.yes b.no ")
if name == "ryan" or "louie" or "aaron":
n = h
else:
n="b"
if n=="a":
print "You ",n,"like your house"
else:
print "You don't like your house"
|
b93f3259f45dbd9ee4ab762f32afd1496a63a75f | claimskg/claimskg-extractor | /claim_extractor/__init__.py | 9,492 | 3.640625 | 4 | from typing import Dict
class Claim:
def __init__(self):
"""
Default constructor, see other constructor to build object from dictionary
"""
self.source = ""
"""The name of the fack checking site, should match the name of the extractor"""
self.claim = str("")
... |
645ce730275d873537f99034a652c649ab6498d3 | anapauregdom/Banco-ExamenProgramacion- | /Bank.py | 1,002 | 3.875 | 4 | #AnaPaulaGemaRegaladoDominguez
class Bank:
#Se define la clase Banco
def __init__(self,name,location):
self.name=name
self.location=location
self.client_dictionary={}
self.number_clients=0
#Se crea un metodo para agregar un cliente
def add_client(self, client):
if self.already_exists(... |
e840fb0f215b1a46e6ae345d61e77190376be636 | WilliamMarti/CCI | /Arrays and Strings/palidrome.py | 837 | 3.875 | 4 | # test if given strings permutation can be a palidrome
# return list of permutations of a given string
def returnpermutations(s, start):
slist = list(s)
swap = start + 1
print (start)
if start == len(s):
return
'''
temp = slist[start]
slist[start] = slist[swap]
slist[swap] ... |
49d149011f2be8856ccb7f53ac0b341b20918d74 | theeric80/LeetCode | /easy/lowest_common_ancestor_of_BST.py | 1,138 | 3.796875 | 4 |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: Tr... |
28f20f90ca59777807ba7d8512073d1b3069c6fd | structuredcreations/Formal_Learning | /python_basics/C1_w6_test1_function.py | 319 | 3.859375 | 4 |
def Computerpay(hr_work,base_rate):
if int(hr_work)<=40:
pay_amount=int(hr_work)*float(base_rate)
else:
pay_amount=(40*float(base_rate))+((int(hr_work)-40)*float(base_rate)*1.5)
return pay_amount
hr_work=input("type number of hours")
base_rate=input("type base rate")
x=Computerpay(hr_work,base_rate)
print(x)
|
22ca6647f7e52fbca18fffeb2d1e351d881d71cb | dmaahs2017/covid-benford-analysis | /src/graphs.py | 2,496 | 3.515625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import os
import math
import utils
def display_freq(freq_tables, filter=""):
for (table_name, table) in freq_tables:
print("===============================================================")
if filter == "":
print(f"Table Name: {table_na... |
b7930fcbb32b4c4ba5c02bff0e09cd97a06967a7 | joeslee94/PythonProjects | /Python101/Translator_Project.py | 333 | 4.21875 | 4 | vowel = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
def translate(phrase):
translation = ""
for letter in phrase:
if letter in vowel:
translation += "g"
else:
translation += letter
return translation
phrase = input("Enter in a word: ")
print(trans... |
ee240acd422ee9d7e41c8ead7434fd216a796724 | Matt-McConway/Python-Crash-Course-Working | /Chapter 8 - Functions/ex8-3_pp141_t-Shirt.py | 229 | 3.625 | 4 | """
"""
def make_shirt(size, message):
print("Your shirt is a " + size + " size.")
print("Your shirt has '" + message + "' written on it.")
make_shirt("medium", "HELLO WORLD")
make_shirt(message="1337", size="large")
|
e274fa306ecfde5e52dafa3a4049c6780f1bc41c | SameerShiekh77/Python-Problems-Solution | /problem27.py | 147 | 4.4375 | 4 | # 27. Write a Python program to calculate the length of a string
text = input("Enter any text to find what is length of text: ")
print(len(text)) |
b251fd6068ed99f9bfec0242013aa5819441b8bf | Maxwell-Banks/search-engine | /search_engine.py | 8,170 | 3.6875 | 4 | """Maxwell Banks
Search Engine
CPE202
"""
import sys
import os
from linear_hash import *
import math
class SearchEngine:
"""A search engine class that builds and maintains an inverted
index of documents stored in a specified directory and
provides a functionality to search documents with query term... |
73066ac81266ec0e02a76eba37fbfe6f0abb4f6b | avelikev/Exercises | /data_structures/binary_trees/3_delete a node/Solution/solution.py | 1,670 | 3.96875 | 4 | # Definition: Binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def delete_Node(root, key):
# if root doesn't exist, just return it
if not root:
return root
# Find the node in the left subtree if key value is less than... |
c841fc009bfacfcd1d91ef2e1e245a659e7f7561 | dhruvanshmoyal01/Data-Structures | /primitive_calculator.py | 992 | 3.578125 | 4 | def calc(num):
minOP = [None for i in range(num+1)]
minOP[0], minOP[1] = 0, 0
# operations x*2 // x*3 // x+1
# calculating the min number of operations
for i in range(2, num+1):
op1, op2, op3 = num, num, num
op1 = minOP[i-1] +1
if i%2 == 0 :
op2 = minOP[i//2] + 1... |
16aee9dffa412f244e0a9722e4cd2b0fd6a21769 | DaDaGoRo/Python | /Prueba_ComparacionStrings.py | 581 | 3.890625 | 4 | print("Hola Mundo")
var = ["Hola Mundo", "X", "Y"]
exit = "Finalizar"
temp = ""
while temp != exit:
temp = str(input("Escribe algo: "))
if temp in var:
print("Lo que escribiste: {} está en la lista".format(temp))
posicion = var.index(temp)
print("Adicionalmente, está en la posición: {}".... |
37ccb90ae036514907e4ecd0e5b82b63a84e3af3 | M-Jawad-Malik/Python | /Python_Fundamentals/29.Operations_on_sets.py | 544 | 4.21875 | 4 | # all operations of set theory : Union,intersection,difference and symmetric difference can be applied#
A={1,2,3,4,5}
B = {3,4,5,6,7,89,32,45,9}
# Difference of two sets A-B#
print('Difference of A and B is : ', A-B)
# Union of two Set AUB#
print('Union of A and B is : ', A | B)
# Intersection of two sets A&B#
... |
4cc50141c483126a03e43509fba7181ab9ad4f76 | pacomgh/universidad-python | /017-sobrecarga-operadores/persona_sobrecarga.py | 647 | 3.96875 | 4 | class Persona:
def __init__(self, nombre):
self.__nombre = nombre
#metodo sobreescrito de la clase padre object
def __add__(self, otro):
#accedemos al nombre del objeto y lo concatenamos con el nombre del otro
#objeto
return self.__nombre + " " + otro.__nombre
... |
9e850bca7503ff02b906b8b8d35361104b76156f | zealpatel1990/3gpp_tagger | /utils/file_utils.py | 426 | 3.546875 | 4 | import json
def get_text_from_file(input_file):
with open(input_file, 'r') as f:
text_content = f.read()
f.close()
return text_content
def write_text_to_file(text, file_name):
with open(file_name, 'w') as f:
f.write(text)
f.close()
def write_json_to_file(dict_value, fil... |
6a7229cbaf4a1113ad6af876621b2e78b8b3db0c | isarvesh/phonebook-demo | /main.py | 2,408 | 4.21875 | 4 | import contacts
from os import system
main_message = """WELCOME TO PHONEBOOK
----------------------------------
**********************************
Please choose:
1 - to add a new contact
2 - to find a contact
3 - to update a contact
4 - to delete a contact
**********************************
---------------------------... |
67f5f040dc84978dbc4ceadb79f00074ff0718af | S-ghanbary98/python_API_Package | /api_request_practice.py | 1,241 | 3.75 | 4 |
# import requests
#
# check_response_postcode = requests.get("https://api.postcodes.io/postcodes/")
#
# if check_response_postcode.status_code == 200:
# print("postcode is valid")
# print("Status code: {}" .format(check_response_postcode.status_code))
#
# else:
# print("OOps something went wrong")
#
#
# i... |
e44069b96bff145fbd809e1101c1983365368bd8 | nayan-mehta/pydemo2 | /Class-9 Exception Handling.py | 2,023 | 4.28125 | 4 | #Basic Example
# while True:
# try:
# x=int(input("Enter an integer:"))
# break
# except ValueError:
# print("That was not a valid int! Try again")
#Try except else
# import sys
#
# print(sys.argv)
# try:
# f=open(sys.argv[1],'r')
# except OSError:
# print("Cannot open",sys.arg... |
ab51bb6a72dfa449d8807e1a9008f69029a32f0d | hugoleonardodev/learning | /python/desafio-015-python.py | 269 | 3.703125 | 4 | #Desafio 015 Python Prof Guanabara
#Car rent: input how many days? how much km? return you pay: R$1,55 p km
#Consider 1 day = 12*7=84 each day, price=(84*d)+(1.55xk)
d=int(input('How many days?'))
k=float(input('How much kilometers?'))
p=float((k*1.55)+(d*7))
print(p)
|
b5b9f851715f3e257a547e69c7e6d976455f335d | billgoo/LeetCode_Solution | /Related Topics/Two Pointers/1721. Swapping Nodes in a Linked List.py | 658 | 3.921875 | 4 | # 1721. Swapping Nodes in a Linked List
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
head_k = ListNode(-1, he... |
615b97fff6245e253cdbe96e8000af47c2c7c7dc | karolinanikolova/SoftUni-Software-Engineering | /2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/08-Text-Processing/01_Lab/05-Digits-Letters-and-Other.py | 864 | 3.96875 | 4 | # 5. Digits, Letters and Other
# Write a program that receives a single string and on the first line prints all the digits,
# on the second – all the letters, and on the third – all the other characters.
# There will always be at least one digit, one letter and one other characters.
# string = input()
#
# digits = ""
... |
ac87c58420db7acd5dff47e0b50b3e5ba4ecf4b0 | tlambrou/Tweet-Generator | /analyze_word_frequency.py | 883 | 3.734375 | 4 | from collections import Counter
import sys
import string
import re
def histogram(source): #9
dictionary = {}
with open(source) as f:
wordList = f.read().split()
for word in wordList:
word = re.sub('[.,:]', '', word)
if word not in dictionary:
di... |
2a4cbd00c1f6a5657b6dedd74ad909cd60ac7e0e | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4140/codes/1674_1105.py | 453 | 3.765625 | 4 | a=input()
print("Entrada: ",a)
a=a.lower()
if(a=="lobo"):
print("Casa: Stark");
elif(a=="leao"):
print("Casa: Lannister");
elif(a=="veado"):
print("Casa: Baratheon")
elif(a=="dragao"):
print("Casa: Targaryen")
elif(a=="rosa"):
print("Casa: Tyrell")
elif (a=="sol"):
print("Casa: Martell")
elif (a=="lula"):
print(... |
5f2c70c6debb449ed53e6be019435dcdc46cf3f2 | vmurali100/prudvi | /sets.py | 455 | 3.59375 | 4 | # cities ={"Bangalore","Hyd","Ram","Ravi"}
# cities.add("Amaravathi")
# cities.update(["Tirupathi"])
# cities.remove("Bangalore")
# cities.discard("Ram")
# cities
# print(len(cities))
# print(cities)
# for a in cities:
# print(a)
newCities = { "Bangalore","Hyd","Ram","Ravi"}
newCities.add("Kochin")
newCities.upd... |
348708c6db2b4c792eb592a49ba3ada75fcee29d | shubhamwaghe/Work-System-Design | /p_chart.py | 3,577 | 3.5625 | 4 | # Author: Shubham Waghe
# Roll No: 13MF3IM17
# Description: WSD-II Assignment-1
import numpy as np
import matplotlib.pyplot as plt
from random import gauss
import Tkinter as tk
import math
# Given data
READINGS_EACH_DAY = 400
desired_limit = 0.05
p = 0.2
RANGE_VALUE = 3
PLOT_RANGE = 2*p
#Stopping criteria
NO_OF_DAYS =... |
76a069f02d6411654cbd484425df97db4b6ce9dd | isthegoal/SwordForOffer | /数学计算/题目34.丑数.py | 1,885 | 3.90625 | 4 | # coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精
'''
题目: 把只包含因子2、3和5的数称作丑数(Ugly Number)。求第1500个丑数
例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
分析: 很明显还是从数字规律来 考虑,而不可能是直接遍历,该怎么利用这一规律呢?
因为都是只包含2、3、5因子,所以这里的规律就是:因为丑数的因子只有 2 3 或者 5,所以丑数必定是 某个丑数 k 的 2... |
5509c5cf210e9ce337260488cfc33afa9e683a6b | dev-iwin/book8-hanbit-python-data-structure-algorithm | /11-01.py | 646 | 3.625 | 4 | def findMinIdx(ary):
minIdx = 0 # 첫번째 값을 가리킴
for i in range(1, len(ary)): # 두번째 값부터 끝까지 비교하기
if ary[minIdx] > ary[i]:
minIdx = i
return minIdx
testAry = [55, 88, 33, 77]
minPos = findMinIdx(testAry)
print('최솟값 -->', testAry[minPos])
def findMaxIdx(ary):
maxIdx = 0 # 첫번... |
f8ca6ce2ddae8bca3d5c2ab923ef20ebb99fcfa0 | THACT3001/PhamTienDung-c4t3 | /hahaha/prime_number.py___jb_tmp___ | 364 | 3.8125 | 4 | n = int(input("Please enter a number: "))
count = 0
if n == 1:
print("n khong la so nguyen to")
elif n == 2:
print("n la so nguyen to")
else:
for i in range(2, n):
if n%i == 0:
count = 1
break
else:
count = 0
if count == 1:
print("n khong la so nguye... |
3e79816afb5a04c4655bbc2b6222539b94482f3b | borko81/basic_python_solvess | /while/report_system.py | 829 | 3.875 | 4 | expected_sum = int(input())
sold_cash = 0
sold_card = 0
total_cash = 0
total_card = 0
product_count = 0
while True:
if total_cash + total_card >= expected_sum:
print(f'Average CS: {total_cash / sold_cash:.2f}')
print(f'Average CC: {total_card / sold_card:.2f}')
break
com... |
68479696e3e85d90a53c4aa14a7121a3d1f55a85 | laubosslink/lab | /python/python-basic-test/MyFirstClass.py | 1,235 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 25 21:02:30 2012
@author: laubosslink
"""
class MyFirstClass:
_hello="default value"
def __init__(self):
self._hello = "default value from init"
@property
def hello(self):
return "from property : " + self._hello
@hello.sett... |
deba2a8df135cdad1259b1a8a7441a85e103be51 | RAVarikoti/DeepLearning-NNs | /ANN.py | 2,634 | 3.59375 | 4 | #! /usr/bin/python3.6
import os
import pandas as pd
import seaborn as sns
import numpy as np
from sklearn import metrics
import tensorflow as tf
#print(tf.__version__)
#print(np.__version__)
df = pd.read_csv("Churn_Modelling.csv")
x = df.iloc[:, 3:-1].values # removing the columns that are not important (row #, cu... |
4254b9e39c64d0e40c3193903654e1eb49c86382 | Dinakar726/New_Challenge | /creating_new_list.py | 511 | 4.5625 | 5 | '''
Two lists are given below. Write a program to create a third list by picking an odd-index element from the first list and even index elements from second.
# Sample Input
list1 = [3, 6, 9, 12, 15, 18, 21]
list2 = [4, 8, 12, 16, 20, 24, 28]
# Expected Output
list3 = [6, 12, 18, 4, 12, 20, 28]
'''
list1 = [3, ... |
1c79e94148e06197e8bffca4d04a12505949d350 | medeiroscwb/py_sqlite_test | /9_sqlite_orderresults.py | 374 | 3.875 | 4 | import sqlite3
conn = sqlite3.connect("customers.db")
c = conn.cursor()
#c.execute("SELECT rowid, * FROM customers ORDER BY rowid DESC") ##orders by rowid descending
c.execute("SELECT rowid, * FROM customers ORDER BY first_name") ##orders alphabeticaly by first name
tab_all = c.fetchall()
for line in tab_all:
... |
49006d177d51fec9bbf1dd0cd31c4c2af2841e04 | taylorcreekbaum/lpthw | /ex11/ex11-3.py | 278 | 3.90625 | 4 | print("What is your favorite color?", end=' ')
color = input()
print("What is your favoriate food?", end=' ')
food = input()
print("What is your favorite hobby?", end=' ')
hobby = input()
print(f"So would you enjoy eating {food} and looking at {color} pictures while {hobby}?") |
7d53a1380aea4c2a56206b05d47ae74e03fbdf7c | damien75/Training-Algos | /HackerRank/dynamic_programming/longest_increasing_subsequence.py | 2,083 | 4 | 4 | from typing import Any, List
class LongestIncreasingSubsequence(object):
"""
Source Hackerrank / Algorithms / Dynamic Programming / The Longest Increasing Subsequence
Input: sequence of integers of size n
Goal: find the length of the longest subsequence of increasing integers in this array
Idea... |
e30661a859b9ae3d3fa234812d406033a816009d | sudhanshu-jha/python | /python3/Python-algorithm/Lists/kthToLast/kthToLast_test.py | 714 | 3.546875 | 4 | from LinkedList import LinkedList
from kthToLast import kthToLast
import pytest
def test_kthToLast():
lst = LinkedList()
lst.insert("Batman")
lst.insert("Superman")
lst.insert("Flash")
lst.insert("Green Lantern")
lst.insert("Wonder Woman")
lst.insert("Hawkgirl")
# Hawkgirl -> Wonder Wo... |
86b5f550a96e952373bdb6b93bb83d37e113431d | OvaLorenzo/Paubot | /Paubot.py | 4,796 | 3.765625 | 4 | # validacion de la matricula, acepta 8 digitos y solo numeros
print('Whats your id?')
while True:
id = input()
if id.isnumeric() == False or len(id) != 8:
print('invalid id')
else:
login = True
# el login = True es para utilizarlo como booleano en el codigo del bot, si es que se... |
39cf5adbb84ddd53c972d2ec73626f8be7dbb344 | ag3000/connect4game | /hello.py | 4,190 | 3.671875 | 4 | #setup
import random
import numpy as np
a = "player 1"
b= "player 2"
firstgo = random.choice([a,b])
print("It is %s's turn" % (firstgo))
activeplayer = firstgo
counterdict = {a : 1, b: 2}
currentboard = np.zeros([6,7],dtype=int)
counterdict[activeplayer]
previousboard = [currentboard]
#function returns true if the col... |
2e745eda9fb86585213b2b5c20dacb8dc7ae8624 | hvaltchev/UCSC | /python3/code/Lab20_Developer_Modules/file4.py | 1,010 | 3.859375 | 4 | #!/usr/bin/env python3
"""The finally can be attached to the try/except since
Python 2.5. But, the finally always happens last, and
doesn't re-raise.
"""
def PrintFile(file_name, fail_on_read=False):
try:
file_obj = open(file_name)
for line in fil... |
f19a2126d0ef9c449d85c1e1084bedae72af14ca | i-me/Python2014 | /exemple_mouvement.py | 1,429 | 3.75 | 4 | from tkinter import *
#définition des gestionnaires
#D'évènement:
def move():
"Déplacement de la balle"
global x1,y1, dx, dy, flag
x1,y1=x1+dx,y1+dy
if x1>210:
x1, dx, dy= 210, 0,15
if y1>210:
y1, dx, dy=210, -15, 0
if x1<10:
x1, dx, dy=10,0,-15
if y1<10:
y1... |
ba1fe197028562c12db08559b539a3b45ccb1b98 | Koneko264/Chapter-9 | /Chapter 9/9.11.py | 1,713 | 3.75 | 4 | class Item(object):
def __init__(self,item_name,item_price,item_quantity):
self.__item_name = item_name
self.__item_price = item_price
self.__item_quantity = item_quantity
def GetItemName(self):
return self.__item_name
def GetItemPrice(self):
return self._... |
ced9a84c6b742ddc8bb88a75cba07b79ef87222d | girlingoggles/training-scripts | /projects/speak_number/speak_number.py | 2,927 | 3.53125 | 4 | #!/usr/bin/env python3
#girlingoggles made this
# phase 4: fix for commented inputs
# 0
# 20000000
# negitives
# decimals
# non number input #parsing input
import sys
import math
def speak_number_ones(one):
if one == 1:
print("one", end = ' ')
elif one == 2:
print("two", end = ' ')
elif o... |
247ad0e2e9a3375646987b574f3c2a47b44468ee | Rvk1605/Python | /Programs/Functionreturn.py | 347 | 3.671875 | 4 | def disp():
def show():
return("Rajveer")
print("My name Is")
return show
ret=disp()
print(ret())
print("---------------------------------------------------------------------------")
#Defining functions Seperately
def disp():
return("My Name Is "+show())
def show():
return "Rajve... |
83c9d348e172b8693112a25060ad5af46eb0e7f7 | nischalshrestha/automatic_wat_discovery | /Notebooks/py/njmei42/kaggle-titanic-with-tensorflow/kaggle-titanic-with-tensorflow.py | 26,360 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Disclaimer:
# For the Titanic dataset, the best performance will likely be achieved by a non-ANN model. But as a student interested in applying artificial neural networks, I thought it'd be a fun/educational challenge! I'm still very very new to machine learning and neural net... |
6f3b7acf404f5b26f5e0b249f6ac80856bc1d2be | zhangzongyan/python20180319 | /day08/e1.py | 378 | 3.640625 | 4 |
import datetime
import e1_module as mye
import turtle
def mytime(mytimestr):
for i in mytimestr:
mye.drawDigit(int(i))
if __name__ == "__main__":
turtle.setup(800, 600, 200, 200)
turtle.penup()
turtle.backward(300)
turtle.pendown()
# 获取当前的年月日
s = datetime.date.strftime(datetime.datetime.now(), "%Y%m%d"... |
76beec2e93dbf6127d97194935c770ea3024b72f | fergussmyth/Hangman | /main.py | 1,354 | 3.796875 | 4 | import os, random, time, assets
f = open('word.txt', 'r')
word = random.choice(f.readlines()).strip().upper()
reveal = list(len(word)*'_')
lives = 7
game_won = False
print('Welcome to HANGMAN!')
time.sleep(1)
print('Game is starting..')
time.sleep(2)
def letter_check(letter, word):
"""
Function to check if ... |
9482d34e26d44cf942b9fe48e5d2c2dbdcd696d1 | saveriogzz/CS_Curriculum | /ALGS200x_Algorithmic_Design_and_Techniques/5.Dynamic_Programming/PC5-2_primitive_calculator.py | 747 | 3.625 | 4 | def greedy_calc(n):
numOperations = 0
history = [n]
while n > 1:
numOperations += 1
if n % 3 == 0:
n /= 3
elif n % 2 == 0:
n /= 2
else:
n -= 1
history.append(int(n))
return numOperations, history[::-1]
def min_ops(n):
... |
1d38a7481b12b73bb712a9c14245b38cfe9240d9 | vividsky/CSES | /trailing_zero.py | 123 | 3.5625 | 4 | from math import factorial
# n = int(input())
n = 100000000
count = 0
while n != 0:
n = (n//5)
count+=n
print(count)
|
4793ea5c44741359cf475c1fc1cfff9feeabd4b3 | rafaelperazzo/programacao-web | /moodledata/vpl_data/79/usersdata/162/43338/submittedfiles/serie1.py | 189 | 3.625 | 4 | # -*- coding: utf-8 -*-
import math
n=int(input('n:'))
soma=0
for i in range(1,n+1,1):
if i%2==0:
soma=soma-(i/(i**2))
else:
soma=soma+(i/(i**2))
print('%.5f'%soma)
|
a9e21f6f19138eb38a9beabbe64fead2973a2eb3 | thominj/reinforcement-learning | /reinforcement_learning/trainers.py | 1,792 | 3.609375 | 4 | import random
import reinforcement_learning.agents as agents
import reinforcement_learning.base as base
class MonteCarloTrainer(base.Trainer):
"""Uses a RandomAgent to select Actions. Stores reward and state between
actions, and reverts to the previous state if the reward for a new action is
lower than th... |
1f805a4dc6a35ca3ddaf964c4c9c7e981cb6fb92 | TianrunCheng/LeetcodeSubmissions | /open-the-lock/Time Limit Exceeded/6-28-2021, 3:22:37 PM/Solution.py | 1,789 | 3.90625 | 4 | // https://leetcode.com/problems/open-the-lock
from collections import deque
class Solution:
def openLock(self, deadends: List[str], target: str) -> int:
# each step we could turn one wheel one slot
# 4 wheels * 2 directions = 8 possible next steps
# bredth first search?
# reach... |
9085ca2129140c610e2b0876f0afb7cd109f4448 | sunday1103/Notebook | /language/python/library/gui/first.py | 3,141 | 3.5 | 4 | from tkinter import Tk, Label, Button, filedialog, Text, Entry
import tkinter
class MyFirstGUI:
def __init__(self, master):
self.master = master
master.title("A simple Telnet Client")
self.file = 0
self.ip = '192.168.172.90'
self.port = 40001
self.timeout = 1
... |
4282b9070d25009eba5a1450b4ea9bd82d99279c | BeholdenArt/Python-plays-Flappy-Bird | /Score.py | 1,002 | 3.5 | 4 | import pygame
pygame.init()
# Main class
class Score:
def __init__(self):
self.count = 0
self.font = pygame.font.SysFont("Consolas", 32)
self.score_x, self.score_y = 10, 40
self.gen_x, self.gen_y = 150, 10
self.pop_x, self.pop_y = 250, 40
def display_score... |
b5fc823983ef67f3e0e5cba0da9b7e82ff616bfd | irkartem/forfun | /homeWork/loopDetect.py | 923 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# DESCRIPTION:
# AUTHOR: artemirk@gmail.com ()
# ===============================================================================
from LinkedList import LinkedList
def loop_detection(ll):
slow, fast = ll.head, ll.head
if fast and fast.next:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.