blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ec8f4237a7cecca0e6e3d53beb5d69a9e94fbf7e | lovekobe13001400/pystudy | /py-cookbook/4.迭代器和生成器/3.使用生成器创建新的迭代模式.py | 392 | 3.96875 | 4 |
#
def frange(start,stop,increment):
x = start
while x<=stop:
yield x
x += increment
for i in frange(0,4,0.5):
print(i)
#函数底层机制
def countdown(n):
print("starting to count from",n)
while n > 0:
yield n
n -= 1
print('Done')
c = countdown(3)... |
c551b28e8d2a07383115b135b52a15ad01a82710 | wingarlo/DailyProgrammer | /2018-6-18.py | 444 | 3.796875 | 4 | import random
import math
'''
[2018-06-18]Challenge #364 [Easy] Create a Dice Roller
Logan Wingard
8/9/2018
'''
random.seed()
def roll(com):
nums = com.split("d")
rolled = [0] * int(nums[0])
for i in range(0,int(nums[0])):
rolled[i] += random.randint(1,int(nums[1]))
sumed = sum(rolled)
return (rolled, sumed)
wh... |
cbcac0c22d776d699b8316709cb38c664b535db6 | hjkqubit/CS134-Sudoku-Solver | /sudoku solver/solver.py | 13,200 | 4.03125 | 4 | #!/usr/bin/env python3
# (c) 2018 Hyeongjin Kim
# a script to solve (or attempt to solve) Sudoku
from module import * # importing useful data structures from module
import ast # used in evaluating a string repr of a list
__all__ = ["solve", "safesolve", "countsolve"]
squares = squares() # list of 81 squares/point... |
f14e54d64a3c3d60f941a5431f4917ae80a8836c | cbielby27/COP1500 | /IntegrationProject3.py | 8,648 | 4.3125 | 4 | # Chelsea Bielby
# Welcome to my integration project! Here, I will showcase what I
# have learned in COP1500 thus far. :)
greeting = "Hi!" * 10
print(greeting)
print("Sorry, I get a little excited sometimes.")
print("Anyway, ", end="")
print("Welcome to my integration project!")
print("What is your name?")
name = input... |
739d34bfea52edfdd6076f339709714689d98401 | rgornik/testniprojekt | /objekt2.py | 773 | 3.859375 | 4 | class Person(object):
def __init__(self, ime, priimek, starost):
self.ime = ime
self.priimek = priimek
self.starost = starost
def show_person(self):
print "Ime: {}\nPriimek: {}\nStarost: {}".format(self.ime,
self.priimek,... |
d37adb67860eb5a34a3b71f490631bdc9c2a1063 | arminAnderson/CodingChallenges | /ProjectEuler/Python/PandigitalPrime.py | 1,250 | 3.71875 | 4 | from math import factorial
def ReverseSectionOfArr(arr, start):
swapAmount = (len(arr) - start)//2
k = len(arr) - 1
for i in range(swapAmount):
i += start
temp = arr[i]
arr[i] = arr[k]
arr[k] = temp
k -= 1
return arr
def GetLexi(arr):
for i in range(factoria... |
a8952a45d4005620456406f27a6f16c3f54825b7 | romanbatavi/kickstarter-python | /bab/bab-4/while4.py | 335 | 3.828125 | 4 | ######################################################
# Nama file: while4.py
######################################################
def main():
# melakukan pengulangan dari indeks 'a' sampai 'e'
ch = 'a'
while ch <= 'e':
print("%c: Hello World!" % ch)
ch = chr(ord(ch) + 1)
if __name__ == "__main... |
915464e9b6fe07e5f154a200ef5ca2cf1dafc245 | karngyan/Data-Structures-Algorithms | /Tree/BinaryTree/Check_Balanced.py | 1,054 | 4.25 | 4 | # Check if a binary tree is height balanced
# abs(height[leftTree] - height[rightTree]) <= 1
# A Binary Tree node
class Node:
# Constructor to initialise node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def check_height(root):
if root is None:
... |
350270a530a218e464ffb346993323941e1b3f8d | Yash-barot25/DataStructresInPython | /Dictionaries/AdvantureGame.py | 1,318 | 3.84375 | 4 | Locations = {0: "You'r standing front of your computer learning python",
1: "You'r at your home 430 mcmurchy south ave",
2: "You'r at tuckshop of brampton towers",
3: "You'r in garden",
4: "You'r inside of shopper's drug-mart",
5: "You'r at 440 mcmur... |
658fd1073a798d5c3503b8b9ceb4a2076dc1974d | Jelle0Bol/nogmaals | /duizelig/even.py | 69 | 3.609375 | 4 | i=20
while(i<=50):
if(i%2==0):
print(i,end=" ")
i=i+1 |
bac32ba211c0c82d4fa164db4c821ce3fbd01516 | robjamesd220/kairos_gpt3 | /Programming_with_GPT-3/GPT-3_Python/semantic_search.py | 1,879 | 3.625 | 4 | # Importing Dependencies
from chronological import read_prompt, fetch_max_search_doc, main
# Creates a seamntic search over the given document 'animal.txt' to fetch the top_most response
async def fetch_top_animal(query):
# function read_prompt takes in the text file animals.txt and split on ',' -- similar ... |
4c6ad64be432581e3695b7ac07979dc6a9187636 | netxeye/Python-programming-exercises | /answers/q18.py | 3,445 | 3.828125 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
import string
class Question18Password(object):
'''
Password Checking:
'''
__slots__ = ('_password')
def __init__(self, password='Welcome@20'):
self._password = password
@property
def password(self):
return self._password
... |
9f24e9ece8196fadd5470c54ffac512deafb3b61 | Somjing/TestGit | /Python/Homework_Lecture_24.py | 190 | 3.8125 | 4 | Name = "Somjing"
Surname = "Pluejinda"
Age = 33
Weight = 62
Height = 170
print("My name's",Name,Surname)
print("Age",Age,"years old")
print("Weight",Weight,"kg")
print("Height",Height,"cm") |
8b4a42ba3793428ca9d602971ebc23eae3429db1 | alferesx/programmingbydoing | /SpaceBoxing.py | 804 | 4 | 4 | weight = float(input("Weight: "))
print("1-Venus")
print("2-Mars")
print("3-Jupiter")
print("4-Saturn")
print("5-Uranus")
print("6-Neptune")
planet = int(input("Choose a planet: "))
if planet == 1:
gravity = 0.78
weight = weight * gravity
print("Weight: " + weight)
elif planet == 2:
gravity = 0.39
weight... |
2d6fbde1050b4487e4255534276138e22cd8aa1e | sherwin090497/PYTHON | /Practice/PracticePython/PracticePython/PracticePython.py | 889 | 4.15625 | 4 |
print("Hello World!")
#Bounded itereration
# use the range function to produce a list of sequential integers
for i in range(5):
print(f"Square {i}: {i*i}")
total = 0
for i in range(1,5):
total = total + i
print(f"Running Sum {i}: {total}")
total = 0
for i in range(-5,0):
total = ... |
64d6857a08ef98089ca9fe1f0667f4cf1211ce7e | liubh1994/algorithm | /Python/select_sort.py | 3,018 | 3.609375 | 4 | def select_sort(data_array, sort_flag=0):
"""
选择排序 O(N^2)
:param data_array: 待排序数组
:param sort_flag: 0: 正序 1: 逆序
:return: 排序后的数组
"""
if len(data_array) <= 1:
return data_array
if sort_flag == 1:
for out_index in range(0, len(data_array)):
max_value = data_arra... |
a6d14e3bfb4ea04d3975fbf75b253b2ca2960dde | mbod/py4corpuslinguistics | /workshops/Nottingham_18July2011/scripts/Task3.py | 1,777 | 4.03125 | 4 | '''
Python for Corpus Linguistics Workshop
University of Nottingham 18 July 2011
Task 3 - Split the reader comments into separate files (one per comment)
'''
import os
import re
#First write a function to output the list of comments to a file
#1. specify name and the arguements required
def output_comments(commen... |
1ac284a3b18cad5b0965cf2feedf0688ad7e3304 | cathuan/LeetCode-Questions | /python/q527.py | 2,408 | 3.890625 | 4 | from collections import defaultdict
class TrieNode(object):
def __init__(self):
self.count = 0
self.children = defaultdict(TrieNode)
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(se... |
e52bd3558f4ab9903cbe6a69ea183e896861e604 | wiput1999/Python101 | /1 Class 1/Homework/7.py | 469 | 3.90625 | 4 | a = int(input("A :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
f = int(input("F :"))
total = a+b+c+d+f
result = (4*a + 3*b + 2*c + 1*d + 0*f)/total
print(result)
'''
defs = (
('A', 4),
('B', 3),
('C', 2),
('D', 1),
('F', 0)
)
sums = 0
weight_sums = 0
fo... |
3149ded825e364499e128d876e90078a2d82071c | TriggerDark/StudyCodes | /PycharmProjects/PythonCodes/01-Based/12-异常/01-异常.py | 610 | 3.875 | 4 |
# 统计一段数字的平均值,要求连输输入,遇到非法字符,提示非法
# 输入的过程中,要继续输入,提示:继续输入?yes继续,no停止
list = []
while True:
x = input("请输入数值")
try:
list.append(float(x))
except:
print("数字非法")
while True:
flag = input("继续输入吗?[yes/no]")
if flag.lower() not in ('yes', 'no', 'y', 'n'):
print("只能输入y... |
25cd373f1a3d43dc71b17738610c918b381e932c | mikeferguson/sandbox_rosbuild | /ex_vision/src/capture.py | 1,618 | 3.671875 | 4 | #!/usr/bin/env python
"""
Example code of how to convert ROS images to OpenCV's cv::Mat
This is the solution to HW2, using Python.
See also cv_bridge tutorials:
http://www.ros.org/wiki/cv_bridge
"""
import roslib; roslib.load_manifest('ex_vision')
import rospy
import cv
from cv_bridge import CvBridge, ... |
d0ed36ef8221058b53e455d55671ab4ab7b7cf89 | vaibhavranjith/Heraizen_Training | /Assignment1/Q45.py | 169 | 3.890625 | 4 | n=int(input('Enter a number:\n'))
sum=n
while sum>9:
sum=0
while n>0:
sum+=n%10
n=n//10
n=sum
print(f"The single digit sum is {sum}") |
5ea9b97c89f3c023ccaa36fae171c42238300aed | gibson1395/CS0008-f2016 | /Chapter 3 Exercise 1.py | 529 | 4.15625 | 4 | number = int(input('Enter a number between 1 and 7: '))
if number == 1:
print('The day of the week is Monday')
elif number == 2:
print('The day of the week is Tuesday')
elif number == 3:
print('The day of the week is Wednesday')
elif number == 4:
print('The day of the week is Thursday')
elif number == ... |
2b8bfaa0dc8dfa96660d67a04db47a383c548c39 | ajeet2808/learn_py | /1essentials/ch3/a10lists.py | 1,259 | 4.65625 | 5 | # list starts with an open square bracket and ends with a closed square bracket
number = [] #empty list
numbers = [10, 5, 7, 2, 1]
# The elements inside a list may have different types. Some of them may be integers, others floats, and yet others may be lists.
mixed = ["Some string", 10, 10.5, True, [1,"a"]]
# Indexi... |
ab9a1d60d27384bb11ea45b4db9f71696499a23b | saurabh1907/leetcode-programming | /src/main/leetcode/detect_capital.py | 502 | 3.6875 | 4 | class Solution(object):
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
if word.upper() == word or word.lower() == word:
return True
else:
word_first = word[0:1]
word_rest = word[1::]
if word_first... |
d9521293fc036142297d102303e11d54e4939d19 | parvathy25/assignment-2 | /que3.py | 205 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 24 13:27:46 2020
@author: HP
"""
def sum_list(items):
sum = 0
for x in items:
sum += x
return sum
print(sum_list([1,2,4,8])) |
36ce87ab5be547f2e307a2016bc4f9aea41b815d | YouFool/python-bible | /hello_you.py | 346 | 4.1875 | 4 | name = input("What is your name? ")
print(name)
age = input ("What is your age?")
print(age)
city = input ("What is your city?")
print(city)
love = input ("What you love doing?")
print("=" * 30)
string = "Your name is {} and you are {} years old. You live in {} and you love {}"
output = string.format(name, age, ci... |
5e06d088fe71986b5530ee0d1bee01960eea1953 | Dyonn/Euler_Project | /euler17.py | 777 | 3.59375 | 4 | import time
start=time.time()
one =191*3
two =190*3
three =190*5
four =190*4
five =190*4
six =190*3
seven =190*5
eight =190*5
nine =190*4
ten =10*3
eleven =10*6
twelve =10*6
thirteen =10*8
fourteen =10*8
fifteen =10*7
sixteen =10*7
seventeen=10*9
eightee... |
44e79bf6525082354c956837514f802fcde9414c | jlucasldm/ufbaBCC | /2021.2/linguagens_formais_e_automatos/listas/semana_13/leitura_multipla.py | 554 | 3.5 | 4 | def solucao(sequence, op):
count = 0
r = 0
for i in sequence:
if i == 'W' and r != 0:
count += 2
r = 0
elif i == 'W' and r == 0:
count += 1
elif i == 'R':
r += 1
if r == op:
count += 1
... |
3ec22d8a57271bca153a3225e78d8a918661c479 | cehan-Chloe/Lintcode | /096PartitionList.py | 845 | 3.78125 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list.
@param x: an integer
@return: a ListNode
"""
def partition(self, head, x):
if h... |
1e7538049e1f8a5636330337e3bb052331039a52 | seahrh/coding-interview | /src/branchbound/zero_one_knapsack.py | 3,916 | 3.8125 | 4 | """
0/1 Knapsack Problem
======================
Given weights and values of N items, put these items in a knapsack of capacity C
to get the maximum total value in the knapsack.
You cannot divide an item, either pick the whole item or don’t pick it (0-1 property).
A single solution is expressed as an boolean array... |
a0110e545f3908f1dd24072d746fed76c1388ebb | Zed-chi/Skillsmart_func_python | /fp_task6.py | 1,005 | 3.734375 | 4 | """
State Monad
Пример с покупками
есть:
- условный человек = {корзина, счет}
- перечень продуктов = []
- условный результат покупок (человек, кол.покупок)
"""
from pymonad import curry, State, unit
@curry
def buy(what, to):
@State
def state_computation(old_state):
if what in items an... |
b690d637454ff0b623d063589e86f4f3ab0dab6b | isZengwen/PythonNotes | /timeit_demo.py | 565 | 3.59375 | 4 | import timeit
#测量代码块的执行时间
c ='''
sum=[]
for i in range(0,1000):
sum.append(i)
'''
t1 = timeit.timeit(stmt="[i for i in range(0,1000)]",number=100000)
t2 = timeit.timeit(stmt=c,number=100000)
print(t1,t2)
print("#"*20)
#测量不含参数函数的执行时间
def doIt():
n = 3
for i in range(n):
print(i)
t3 = timeit.timeit(... |
89fe411b071b5a5d1b7f169efe3dcb71b5750c81 | JAKER3/Dice-Game | /Dice Game/Dice Game.py | 8,415 | 3.5 | 4 | import random
import time
import os
import uuid
import hashlib
import operator
def see_leaderboard():
see = True
while see == True:
reply = input("Would you like to see the whole leader board, enter y/n or \nq to completely quit the game: ")
if reply == 'q':
assure = inp... |
3227ce5391684687202d137a73127546b220c12d | iampaavan/Pure_Python | /Exercise-13.py | 281 | 4.125 | 4 | import calendar
"""Write a Python program to print the calendar of a given month and year."""
y = int(input(f"Enter the year: "))
m = int(input(f"Enter the month: "))
month = calendar.month(y, m)
print(f"Year and Month:{month}")
c = calendar.monthrange(2019, 4)
print(c)
|
0a6ab33f55d7ab380d94a25d89c0effb11cb7ca0 | prichakrabarti/python_guided_project | /q01_create_class/build.py | 1,904 | 4.25 | 4 | import math
class complex_number:
'''The complex number class.
Attributes:
attr1 (x): Real part of complex number.
attr2 (y): Imaginary part of complex number.
'''
#There are some functions you want to call as soon as you initialize my class- so as soon as I call the class, the thing with __init_... |
7e7a2e4a236ab71bad2d563a454191a68e14cba9 | dchang-pragma/cloudbit | /python3-tutorial/class_rabbit.py | 890 | 4.0625 | 4 | class Rabbit:
"""A simple example class"""
genus='Oryctolagus'
specie='cuniculus'
#tricks=[] #class variable
def __init__(self, name, breed, color):
self.name = name
self.breed = breed
self.color = color #instance variable
self.tricks = [] # creates a new empty lis... |
7e4e274e60a51173e947e0febc15873e65747c47 | Toadstool/LearnPython | /Lab1/z3.py | 304 | 3.5 | 4 | from random import randrange
r = randrange(100)
u = int(input("podaj liczbe od 1 do 100"))
while(r!=u):
if(u>r):
print("za duzo")
else:
print("za malo")
i = input("sprobuj")
if(i=="q"):
break
u = int(i)
if(r==u):
print("zgadles")
|
f56b07726849a4ce0d96e8ea37b512420e9b9a0f | c-eng/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 552 | 4.125 | 4 | #!/usr/bin/python3
"""Read n lines function
"""
def read_lines(filename="", nb_lines=0):
"""Reads n lines from a file
Args:
filename (str): filename/filepath
nb_lines (int): numbr of lines to read
"""
count = 0
if type(nb_lines) is int and type(filename) is str:
with open(f... |
6918347c1d0b35a227edcc4b95dfa0db17a984ae | RatnamDubey/DataStructures | /Educative/Data Structures for Coding Interviews in Python/Challenge 1: Remove Even Integers from List.py | 425 | 3.84375 | 4 | ##########################################
### Remove the Even Integers from the List
###########################################
class operations_maths():
def remove_even(self,list):
newlist =[]
for values in list:
if values % 2 != 0:
newlist.append(values)
... |
af884e44be7c39502058459bb629d9233f9c05d1 | catr1ne55/stepik_python_basics | /1/1.2.1.py | 117 | 3.609375 | 4 | objects = [1, 2, 1, 2, 3]
ans = []
for obj in objects:
if obj not in ans:
ans.append(obj)
print(len(ans)) |
aa64df827e7c301db3613a65a72b1009347aff17 | TheNite/Python3-BootCamp | /Milestone Project 1/tictactoe.py | 5,577 | 4.1875 | 4 | """
Play tic tac toe with a friend
"""
tic_tac_toe_board = {
"upper_left": " ",
"upper_middle": " ",
"upper_right": " ",
"middle_left": " ",
"middle_middle": " ",
"middle_right": " ",
"bottom_left": " ",
"bottom_middle": " ",
"bottom_right": " ",
}
player_piece = {
"player1":... |
23ea054cc4481b2515a4475d8668bf3f5dd41f23 | bouzidnm/python_intro | /notes_20Feb2019.py | 1,752 | 4.4375 | 4 | ## Notes for 20 Feb 2019
## Lists, Indexing, Slicing
## Lists
## Square brackets, are ordered and changeable
nums = [1, 2, 3, 4, 5] #same element types, int
fruit = ['apple', 'banana', 'strawberry'] #same element types, str
random = ['bob', 2, 3.14, True]
# Review from last week
type(nums)
# it's a class list
## Ind... |
240adeb28c223fd42ce8f5b99d4f630b85550b5a | tonylattke/hsb_gesture_recognition | /oldVersions/HandTrackingOnly/Triangle.py | 1,285 | 3.5 | 4 | # HSB - Computational Geometry
# Professor: Martin Hering-Bertram
# Authors: Filips Mindelis
# Tony Lattke
from numpy import sqrt, arccos, rad2deg
class Triangle:
cent = []
rect1 = []
rect2 = []
# Contructor
def __init__(self, cent, rect1, rect2):
self.cent = cent # tupleToLi... |
e3e5764e25d6a10d2121c64f4f4d870805a7b6c3 | abhi7542/hello | /abhi kr.py | 391 | 3.671875 | 4 | print('hello world')
a ='abhishek kumar'
b =22
print(b)
print(a)
'''yrfrf6yurfwy6rfy'''
print('heappy learning \n \nwelcom to python')
ac=10
bc=['abhishek','5']
print(ac,bc)
a,b,c=20,30,40
print(a,b,c)
f=10.45
print(type(f))
print(bc)
bc[1]='prince'
print(bc)
print(c>a)
print(4*567)
print(40%7)
t... |
6b650deb24d3cdc9656de68240a12db934ca73b3 | AntaresT/PyRP19 | /RegEx/python_brasil_19_talk-master/arquivos/1.py | 507 | 3.84375 | 4 | # -*- coding: utf-8 -*-
import re
# Ver todas as funções e constantes
# print(dir(re))
# findal sempre retorna uma lista com string do pattern que foi encontrado
from re import findall
print(re.findall("f", "fff"))
result = re.findall("xu", "xu")
print(type(result), len(result))
print(result)
result = re.findall(... |
72ba8dca05d9a480f57dc1db308cd9923f2d3d8e | hancse/model_rowhouse | /House model_2R2C_Python/house_model/configurator.py | 6,553 | 3.6875 | 4 | """
A certain Python style gives the modules (*.py files) names of a profession:
in this style, the module that encapsulates the parameter configuration can be called
configurator.py
the module performs the following tasks:
1. read the input parameters for the model simulation from a configuration file
"Pythonic" co... |
964743dda3bcca61966097b4af145a9a7d202d96 | JonyHM/BOT-DepreciacaoVeicular | /CalculaDepreciacao.py | 1,491 | 3.5625 | 4 | # encoding: utf-8
from datetime import datetime
import locale
locale.setlocale(locale.LC_ALL, '')
class CalculaDepreciacao(object):
def __init__(self):
self.ano = 0
self.valorVeiculo = ''
self.anoAtual = datetime.now().year
self.idadeCarro = 0
self.caractere... |
86784a8dab74b99064fb2ab93bec56d59f99796a | NihalAnand/practice | /longest_prefix.py | 225 | 3.78125 | 4 | def longest_prefix(s):
n=len(s)
for res in range(n//2,0,-1):
prefix=s[0:res]
suffix=s[n-res:n]
if(prefix==suffix):
return res
return -1
s='xxnihalxx'
print(longest_prefix(s)) |
7948b8a00c4865bf3191171862c32daca2bbda81 | skjaas/oops | /oop/inheritance/in8.py | 1,518 | 4 | 4 | class Calculator:
def addition(self,num1,num2):
self.a=num1
self.b=num2
return (self.a+self.b)
def sub(self,num1,num2):
self.a=num1
self.b=num2
return (self.a-self.b)
def mul(self,num1,num2):
self.a=num1
self.b=num2
return (self.a*sel... |
5f8c561702d9390267dd0c7930d904d916514754 | ParkMyCar/MoneyManSpiff | /arbitrage/graph.py | 6,558 | 3.640625 | 4 | """
Graph objects used for Money Man Spiff's arbitrage engine
At it's core is a 2D Dictionary aka Dictionary of Dictionaries
Author: Parker Timmerman
"""
from decimal import *
from sys import float_info
from typing import List, Tuple
MAX_FLOAT = float_info.max
class Edge():
""" An edge object to be used for arbi... |
e5187d1106908965a1ab81f09896465f95980405 | chiffa/Karyotype_retriever | /src/basic_drawing.py | 231 | 3.546875 | 4 | import numpy as np
from matplotlib import pyplot as plt
def show_2d_array(data, title=False):
if title:
plt.title(title)
plt.imshow(data, interpolation='nearest', cmap='coolwarm')
plt.colorbar()
plt.show() |
f50c4dd2c07db5b1b8d6f74d7b7b9ef52c719ed7 | Sfreeman99/Gas-Pump | /gas_shell.py | 1,749 | 3.53125 | 4 | import time
import gas_core
import disk
from os.path import isfile
def prepay():
inventory = disk.open_inventory()
money = input("How much money would you like to put in?\n$: ")
gas_type = input("Which gas would you like to choose?: \n\tpremium = 2.49\n\tregular = 2.07\n\tmid grade = 2.10\n")
print('pum... |
8a066c578a1bc603693e22f3dea8d7a86d80fc1b | osamamohamedsoliman/Strings-1 | /Problem-1.py | 993 | 3.703125 | 4 | # Time Complexity :if two arrays sorted average O(n)
# Space Complexity :O(n)
# Did this code successfully run on Leetcode : yes
# Any problem you faced while coding this : no
import collections
class Solution(object):
def customSortString(self, S, T):
"""
:type S: str
:type T: str
... |
a62f6f216ab58d07dc2d44b08eabf58c503b0575 | peiranli/AI | /2048/ai.py | 9,334 | 3.515625 | 4 | from __future__ import print_function
import copy
import random
MOVES = {0: 'up', 1: 'left', 2: 'down', 3: 'right'}
ACTIONS = [(0, -1), (-1, 0), (0, 1), (1, 0)]
class State:
# the tile matrix, player's turn, score, previous move
def __init__(self, matrix, player, score, pre_move):
self.tileMatrix = copy.deepcopy(m... |
ad86cc27b27677585950cca7e29ec5bacd83b051 | daniel-reich/turbo-robot | /5xPh4eEAtpMdXNoaH_7.py | 810 | 4.03125 | 4 | """
Given a string `s`, return the length of the longest palindrome that can be
built with those letters.
### Examples
longest_palindrome("a") ➞ 1
longest_palindrome("bb") ➞ 2
longest_palindrome("abccccdd") ➞ 7
longest_palindrome("") ➞ 0
### Notes
N/A
"""
def longest_palindrome(... |
eba37bc2916ed1a0e963e42e193e961e1679c48a | MDRODGERS17/Apprenticeship-Workspace | /Python Practice/mario.py | 367 | 4.0625 | 4 | from cs50 import get_int
while True:
# Prompts for height
height = get_int("Height: ")
# Reprompts for height if positive number 1-8 isn't inserted
if height >= 1 and height <= 8:
break
# Iterates through each row
for i in range(height):
# Prints spaces
print(" " * (height - i - 1), e... |
4c44784fdb0bedb4d5f9a34d867a10310d8824da | saumyaagrahari123/loop | /q53prime number.py | 198 | 4.1875 | 4 | prime=int(input("enter the number"))
a=1
b=0
while a<=prime:
if (prime%a==0):
b=b+1
a=a+1
if b==2:
print("it is a prime number")
else:
print("it is not prime number")
|
76d752fd634565f7aee4b36e841fa13f68f38829 | Nitin2611/15_Days-Internship-in-python-and-django | /DAY 3/task5.py | 110 | 3.703125 | 4 | x = 46
y = 53
if x > y:
print("x is greater number")
if y > x:
print("y is greater number")
|
261bf2e05686d0d622fe3b60b1a9e5f4e916e130 | shaurya950/code_forces | /81A.py | 277 | 3.71875 | 4 | t = int(input(""))
for j in range(t):
n = int(input(""))
if n == 2:
print(1)
elif n == 3:
print(7)
else:
temp = ""
if n % 2 == 0:
for i in range(n//2):
temp+="1"
else:
temp = "7"
n = n - 3
for i in range(n//2):
temp+="1"
print(int(temp))
|
3aadb6fe1391236c0f09b23175dc42e97fd8c5f8 | a01747686/Mision-03 | /AsientosEnEstado.py | 811 | 3.578125 | 4 | #Autor: Samantha MArtínez Franco A01747686
#Descripción: calcular cuanto va a pagar una persona por comprar boletos de un estadio en diferentes clases
def calcularPago(asientosA, asientosB, asientosC): #función que calcula pago total de los asientos
pagoA=asientosA*925
pagoB=asientosB*775
pagoC=asie... |
1756e503720a4abe403175e0badc53d1af92b0b1 | wolfcomm/python | /whatisyourname.py | 174 | 4.1875 | 4 | x = int(input('Enter digit?\n'))
print('Your digit is:')
print(x)
if x > 10 :
print('X is greater than 10')
if x < 10 :
print('X is fewer than 10')
print('All done')
|
713083164b492f393e507bf77efb8442949e8f99 | huesca92/Data_Science | /Python_Basico/ejercicios_reto/area_triangulo.py | 1,206 | 3.953125 | 4 | def run():
print('Calculemos el area de un triangulo')
base = float(input('Escribe el valor de la base: '))
altura = float(input('Escribe el valor de la altura: '))
A = area_triangulo(base,altura)
print('El area de tu triangulo es: ' + str(A))
decision = input('¿Quieres saber que tipo de... |
19b6c4dd395805a1863eeb5b1f9fbf05058ad445 | effyhuihui/leetcode | /interviews/interview.py | 962 | 3.6875 | 4 | def twosum(root, target):
def dfs(root1, root2, target):
if not root1 or not root2:
return False
if root1.val+root2.val == target and root1 != root2:
return True
if root1.val + root2.val > target:
if root1 == root2:
return dfs(root1.left,root)
else:
return dfs(root1.left,root2) or dfs(root1,... |
6b0aac3c8edb07542651a14cccc4f304b520e753 | evillella/ProjectEuler | /Problem50.py | 1,870 | 3.84375 | 4 | """
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
Which prime,... |
84e90681391399ab49551ecbfaf5566f25edc9ff | yangguolong828/HogwartsLG5-ygl | /sdf.py | 109 | 3.59375 | 4 | a,b = 0,1
while a < 10:
print(a)
print(b)
a,b = b, a+b
print("a的值为",a, "b的值为",b)
|
caefb9f41af9cfa0eaac48cda89db518b53a22c6 | zmcneilly/hackerrank | /default/primes.py | 1,691 | 3.890625 | 4 | from math import *
from bitarray import bitarray
class PrimeNumbers():
"""
This class is a special object for interacting with prime numbers
"""
def update_prime(self, new_max):
"""
This updates the object which contains the list of prime numbers
"""
self.primes = bitar... |
d3dfe5b8d33ea82a8ab7a07b8ee1dec0d9e5a9cd | Kristjaan/Python_practice | /fizzbuzz.py | 305 | 4.09375 | 4 | #!usr/bin/env python3
# Homework 9.2: FizzBuzz
num = int(input("Select a number between 1 and 100: "))
for i in range(1, num+1):
if i % 5 == 0 and i % 3 == 0:
print("fizzbuzz")
elif i % 3 == 0:
print("fizz")
elif i % 5 == 0:
print("buzz")
else:
print(i)
|
c621b6b9a6d1b9f8c07ffd9a5fcbd5c334a1fd41 | karthik-siru/practice-simple | /array/Search_&_Sort/sortbysetbits.py | 848 | 3.6875 | 4 | class Solution:
def countBits(self,a):
count = 0
while (a):
if (a & 1 ):
count += 1
a = a>>1
return count
# Function to sort according to bit count
# This function assumes that there are 32
# bits in an integer.
def sortByS... |
b477ae716637fb3d3f4478724bdb3eb138abfa0c | AErenzo/Python_course_programs | /TicTacToe.py | 4,605 | 4.03125 | 4 | import random
# function that prints of the board
def printBoard():
print('+---+---+---+')
print('|', board[0], '|', board[1], '|', board[2], '|')
print('+---+---+---+')
print('|', board[3], '|', board[4], '|', board[5], '|')
print('+---+---+---+')
print('|', board[6], '|', board[7], ... |
b772337eacbb8e8c943933401dca663eb286eeab | HeangSok-2/Tkinter | /test6_images.py | 517 | 3.515625 | 4 | # Acknowledgement: Dr John (codemy.com)
from tkinter import *
from PIL import ImageTk, Image
# tkinter accept only two type of image files (EX: gif); therefore, we use PIL to use more type of image file
root = Tk()
root.title('I am meow')
icon = 'totoro.jpg'
img = ImageTk.PhotoImage(Image.open(icon))
# icon= PhotoIma... |
92193cfae3c727a6938a13d563e1154fc3195145 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_1_neat/16_0_1_rwd_problem1.py | 634 | 3.734375 | 4 | #input() reads a string with a line of input, stripping the \n at the end
def solution(n):
"""
:type n: int
:rtype : int
"""
if n is 0:
return 0
else:
dic={}
count=0
base=n
while True:
temp=n
while temp:
digit=temp%10
if digit not in dic:
dic[digit]=1
count+=1
... |
cefbd067730b07d0922a7f6030d7e91e7b160fae | ofarukaydin/ctci-python | /LinkedLists/intersection.py | 404 | 3.78125 | 4 |
def intersect(list1, list2):
if list1[-1] != list2[-1]:
return None
else:
longerList, smallerList = (list1, list2) if len(
list1) > len(list2) else (list2, list1)
offset = abs(len(list1) - len(list2))
for i in range(len(smallerList)):
if (smallerList[i]... |
dcc4d2a6ef44114f8ba72e303f8ef95894931adc | dre1970/python-exercises | /list.py | 317 | 4.25 | 4 | list_len = int(input("How many elements are in your list? "))
u_list = []
for i in range(0, list_len):
u_list.append(float(input(f"What is the {i}th element of your list? ")))
bound = float(input("What do you want to search for numbers less than? "))
new_list = [x for x in u_list if x < bound]
print(new_list)
|
b0bbc149fd34675a2c023e02d3b3e8cf48cb8878 | WuPedin/LeetCodePractice | /LintCode/BFS/69_Binary Tree Level Order Traversal_Single Queue.py | 822 | 3.671875 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: A Tree
@return: Level order a list of lists of integer
"""
def levelOrder(self, root):
res = []
# ... |
99ffc93a22ed6b92398f06e1ece1b843dc220582 | martinseener/pycaesarcrypt | /pycaesarcrypt.py | 1,005 | 3.734375 | 4 | #!/usr/bin/env python
# # -*- coding: utf-8 -*-
__version__ = '1.0.0'
class pycaesarcrypt(object):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def caesar(self, string, shift):
result = ''
for char in string:
if char.isalpha():
index = (self.alphabet.find(char.lower())... |
8635ac59da24730ac55fcd1252b1f4b5adc8456d | nicolageorge/play | /amazon/graphs.py | 1,583 | 3.796875 | 4 | class Node:
def __init__(self, value, neighbors=None):
self.value = int(value)
if(isinstance(neighbors, list)):
self.neighbors = neighbors
elif(isinstance(neighbors, string)):
self.neighbors = neighbors.split(',')
def add_neighbor(self, node):
self.neighb... |
9597f6451cce734d98ee2201d9a3f50e2082e2b7 | vaibhav223007/Python_Code | /Random_Questions/03_split_string.py | 144 | 3.984375 | 4 | # WAP to split the string and store in a list
def splitting(string):
return string.split()
print(splitting("Hello world how are you?"))
|
cd9a5b158f92c453b790d9e8eb5febb3e4b3ea09 | sudeep0901/python | /src/8.functions.py | 741 | 3.765625 | 4 | a = 10
print(id(a))
def showvar(X=a): # Default argument will not change
print(X, id(X))
a = 20
print(id(a))
showvar()
def foo(x, items=[]):
items.append(x)
return items
print(foo(1))
print(foo(2))
print(foo(3))
print(foo(4))
def foo1(x, items=None):
if items is None:
items =... |
6902f385ee83e38a63d03b4d1547def55e6cace1 | chanbi-raining/m_g_stagram | /follow.py | 15,281 | 3.5625 | 4 | from bson.son import SON
def followNew(db, userid):
"""
Get the followers.
This function updates information that is user's followers or followings.
Note that if a user asks following to someone, the follower's information should be also updated.
Remember, you may regard duplicates and the situatio... |
737e36297577a685e90d9f114145d46a43c0f274 | farhantk/python | /15.MoreOnList.py | 296 | 3.5625 | 4 | data = ["meja","kursi","buku"]
print(data)
# Menambah list
data.append("kartu")
print(data)
# Meremove list
data.remove("kursi")
print(data)
# Menambah dibagian tertentu
data.insert(2,"meja")
print(data)
# Menghitung benda di list
jumlah = data.count("meja")
print("jumlah meja ada ",jumlah)
|
45d2f570f07ca47b8f06dbf780b2ace9bbfca5cd | qimanchen/Algorithm_Python | /python_interview_program/file_operate/get_file_path.py | 770 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2019-06-04 21:43:51
# @Author : Qiman Chen
# @Version : $Id$
"""
这个函数接收文件夹的名称作为输入参数
返回该文件夹中文件的路径
以及其包含文件夹中文件的路径
"""
import os
def print_directory_contents(s_path):
"""
:param s_path: 输入文件夹 -- 完整的路径
输出该文件夹包含文件和文件夹的所有完整路径
"""
for s_child in os.listdir... |
e39cce2bbff9bd1054852b3e5bdec6aa218731aa | lexusmem/Udemy_Python3 | /Fundamentos_Projetos/area_circulo_v6.py | 647 | 3.78125 | 4 | #! python
# Shibang - Indicação do interpretador que será utilizado p executar o script
# particionar o programa em varios arquivos diferentes
# podendo trabalhar com importações de
# pacotes e modulos
# ferramentas disponiveis no python
from math import pi
# Forma para importar apenas o PI do modulo Math
print(f'Va... |
89b996cc0667d8394a951229e0ce75bd383de542 | DarNattp/python3-practice-by-snakify | /While loop/The largest element.py | 416 | 4.09375 | 4 | '''Given a list of numbers. Determine the element in the list with the largest value. Print the value of the largest
element and then the index number. If the highest element is not unique, print the index of the first instance.'''
a = input()
b = a.split()
for i in range(len(b)):
b[i] = int(b[i])
max_a = max(b)... |
3de9649aeefbd27357fc9833a05a6842d9f02070 | PeterZhangxing/others | /test_random.py | 750 | 3.71875 | 4 | #!/usr/bin/python3.5
import random
def check_random(n):
if n.isdigit():
n = int(n)
else:
return "Invalid Input,we can only accept one number as parameter!Please retry!"
checkcode = ''
for i in range(n):
current_random = random.randrange(0,n)
if i == current_random:
... |
fa2483e1dc1055c06a724da0f4204bdfd5c35ec4 | biyoner/-offer_python_code | /17打印从1到最大的n位数.py | 1,511 | 3.6875 | 4 | #coding=utf-8
# author:Biyoner
### Method 1
def print1ToN1(n):
if n<=0:
print 0
return 0
number = ["0"] *(n+1)
while not simulateADD(number):
PrintValue(number)
def simulateADD(number):
isOverflow = False
l = len(number)
for i in range(l-1,-1,-1):
if... |
044888afa9b99c65872aa2dfd5542fb107220676 | MrHamdulay/csc3-capstone | /examples/data/Assignment_4/grcdea001/ndom.py | 710 | 3.578125 | 4 | def ndom_to_decimal(a):
stra = str(a)
decimals = 0
for i in range (len(stra)):
decimals = (decimals) + int(stra[i])
decimals = decimals*6
return decimals//6
def decimal_to_ndom(a):
stra = str(a)
sndom = ""
for i in range (len(stra)+1):
whole =... |
0240d97e74013d07c626fec7cc280f64afce56a8 | vishalkmr/Algorithm-And-Data-Structure | /Linked Lists/Merging.py | 1,486 | 4.3125 | 4 | '''
Merg two sorted linked-list into one linked-list
Assume that both the given linked-list are in Ascending order
Example :
list-1 contains 1,3,6,7,9
list-2 contains 2,4,8,10
meged list : 1,2,3,4,6,7,8,9,10S
'''
from LinkedList import LinkedList
def merg(first_linked_list,second_linked_list):
"""
Retu... |
5a336adccd9c89951b9431bb01a1b3ac61f5a38a | nepomnyashchii/TestGit | /old/videos/practice.py | 1,589 | 4.125 | 4 | # print("Hello\nWorld")
# print("My\nmonkey")
# print("Alecismyfavourite\ncharacter")
# print(20==20)
# weather = "fall"
# if weather == "summer":
# print("Weather is good today")
# elif weather == "winter":
# print("Weather is horrible today")
# else:
# print("I am out today")
# weather = "summer"
# if no... |
e368572edb5e8313f14ac4a667eeafde6330f43d | sharmasourab93/CodeDaily | /ProblemSolving/CombinationsOfString.py | 237 | 3.765625 | 4 | def permute(a,l,r):
if l==r:
print(''.join(a))
for i in range(l,r+1):
a[l],a[i]=a[i],a[l]
permute(a,l+1,r)
a[l],a[i]=a[i],a[l]
string="ABC"
n=len(string)
a=list(string)
permute(a,0,n-1) |
0e31b5a9aece344d77faee6d05b8dd0ddf9ba8d9 | VagnerGit/PythonCursoEmVideo | /desafio_035_analisando_triângulo_v1.0.py | 482 | 4.125 | 4 | '''Exercício Python 35:
Desenvolva um programa que leia o comprimento de três retas e diga ao
usuário se elas podem ou não formar um triângulo.'''
a = float(input('\033[36mdigite comprimento da 1º reta '))
b = float(input('digite comprimento da 2º reta '))
c = float(input('digite comprimento da 3º reta\033[m '))
if a... |
7bd5b8e777674670c054a036ab406f5a7b1fc0fd | abbybernhardt/Bernhardt-MATH361B | /NumberTheory/N5_Divisors_Bernhardt.py | 402 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 20:00:32 2019
@author: abigailbernhardt
"""
#%%
def divisors(n):
divisorlist = []
ii = 1
while ii < n: # proper divisor so not = to n
if (n % ii==0):
divisorlist.append(ii)
ii += 1
return divisorlis... |
5628ee497110a2386195bde95cc904fb82053f03 | bashir001/logistic-regression | /logistic regression.py | 1,054 | 3.78125 | 4 |
# logistic-regression
#import the necessary modules/packages
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
#read the datasets
df = pd.read_csv('[titanic (1).csv](https://github.com/bashir001/logistic-regression/files/6287173/titanic.1.c... |
d897e1fc497347aa60bcb7070815442b0c46da62 | omi23vaidya/MachineLearningFun | /dogs.py | 498 | 3.6875 | 4 | ##Learning how selection of a feature matters
import numpy as np
import matplotlib.pyplot as plt
greyhounds = 500
labs = 500
#greyhound's height would be between 24 and 32
greyhound_height = 28 + 4 * np.random.randn(greyhounds)
#lab's height would be between 20 and 28
lab_height = 24 + 4 * np.random.randn(labs)
# ... |
be9657f21e559443b23501c93cdc9bf8bdfa753d | edicley/WikiPython-Exercicios | /EstruturaDeDecisao/EstrutDecisao_17.py | 367 | 3.859375 | 4 | """
Faça um Programa que peça um número correspondente a um determinado ano e em seguida informe
se este ano é ou não bissexto.
"""
print('Informe um ano e lhe direi se ele é bissexto ou não.')
ano = int(input('Informe um ano: '))
if ano % 4 == 0 and ano % 400 == 0:
print(f'{ano} é um ano bissexto.')
else:
pr... |
08341da568960ae210848db02a85d7e2be3e9b5e | buckeye-cn/ACM_ICPC_Materials | /solutions/buckeyecode/9.py | 199 | 3.625 | 4 | n = int(input())
lines = [
input().split(' ')
for i in range(n)
]
words = {
line[0]
for line in lines
}
print(len(set(
word
for line in lines
for word in line
) - words))
|
23c9ba644d6c01a7f88742c512bbbd0c427aaf93 | mfbx9da4/mfbx9da4.github.io | /algorithms/10.7_missing_int.py | 3,180 | 3.515625 | 4 | # An input file with four billion non-negative integers
# Generate an integer not contained by the file with 1GB of mem
# Follow up: what if all numbers are unique and you only
# have 10MB of memory
# p416
import random
import sys
max_64 = sys.maxsize
max_32 = 2**32 - 1
large_filename = 'large_number_of_ints.txt'
sm... |
2eef73c42a31960e45c1e183382bd36533058770 | cherryzoe/Leetcode | /42. (Lint)Maximum Subarray II.py | 1,756 | 3.84375 | 4 | # Given an array of integers, find two non-overlapping subarrays which have the largest sum.
# The number in each subarray should be contiguous.
# Return the largest sum.
# 这一题有点像buy stock III, 分割两边然后再求最大值的做法,所以采取类似的做法
# 如果采取maximum subarray的办法去求每一个index的两边,则需要 O(n^2)
# 这里才去和buy stock III类似的题目,但是略有不同 对于左边,用两个array lef... |
4b14a51b9f6998bf0774d38bb47113887c85d197 | nmt/AdventOfCode | /2019/01/01-b.py | 729 | 3.8125 | 4 | #!/usr/bin/env python3
# IN: List of module masses, each on a separate line
# OUT: Sum of the fuel requirements for all modules (taking into account the fuel requirements for the fuel itself)
sumTotalFuelReqs = 0
def calculateFuel(mass):
fuel = mass/3 - 2
if fuel > 0:
return fuel + calculateFuel(f... |
f6a27a3567debbcd8ac543bda53ff524a89eaf6d | gabgerson/coding-challenges | /data-algo/fraudulent_notifications.py | 1,085 | 3.546875 | 4 | import bisect
def activityNotifications(expenditure, d):
#sort array from 0 to d -1
days = sorted(expenditure[0:d])
#middle = d//2
mid = d//2
#save num notifications to variable
notifications = 0
#loop through expenditures from d to end
for i in range(d, len(expenditure)):
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.