blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
fbfce09d15876554a70547af7a3b94b1badf17fc | NavireGALR/Navire | /ekawa/exo_PYTHON/courvid_proc/grid.py | 2,377 | 3.6875 | 4 | import turtle
import random
class Position(object):
"""docstring for Position"""
def __init__(self, x, y):
self.x = x
self.y = y
class Zone(object):
"""docstring for Zone"""
SIDE = 100
def __init__(self):
self.corner1 = 0
self.corner2 = 0
rand_num = random.randint(1,100)
if rand_num in range(1,69):... |
b03112d5e1875775953922099e1d26b9473ff703 | jeffsantos/curso-ebape-prog-aplic-cur2018-turma2021 | /2-python/py01_io.py | 95 | 3.625 | 4 | nome = input("Nome: ")
#print("Oi " + nome) #old way!!!
print(f"Oi {nome}") #formated strings!! |
c50dee32228d261299f17daa2f38925d6505763c | HauaM/Study_Python | /Double_Dice_While.py | 242 | 3.78125 | 4 | #03_double_dice_while
import random
while True:
throw_1 = random.randint(1,6)
throw_2 = random.randint(1,6)
total = throw_1 + throw_2
print(total)
if throw_1 == 6 and throw_2 ==6:
break
print('Double Six thrown!')
|
bd913a4db758eb5c4211d985f47542a414774479 | HauaM/Study_Python | /TeamLab/slicing_.operation.py | 684 | 3.890625 | 4 | color = ["red","blue","green"]
color2 = ["orange","black","white"]
print(color+color2)
#두 리스트 합치기
len(color)
#리스트 길이
color[0]="yellow"
#0번째 리스트의 값을 변경
print(color*2)
#color 리스트 2회 반복
'blue' in color2
#문자열 'blue'가 color2 존재 여부 반환 true or false 밖에 안들어감
total_color = color + color2
color.append("white")
#리스트에 "white"추가
c... |
6a3c652ddfed6714da94dd12a06a9e5f8e2838a5 | Rajesh3601/100-Days-Of-Coding | /Day 1 - 10/Day 4.py | 1,525 | 3.96875 | 4 | # 11
# Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input
# and then check whether they are divisible by 5 or not. The numbers that are
# divisible by 5 are to be printed in a comma separated sequence.
# Example:
# 0100,0011,1010,1001
# Then the output should be:
# 1010
# va... |
f29ee3ebdde39c8437b4c05a3fcca8868b52a3a1 | aahana-khajanchi/python | /pythonPrograms/primeDiv.py | 596 | 3.90625 | 4 | #num = int(input('enter the num'))
#x = range(num)
# for i in x :
# if( num/i) == 0 :
# print(i)
score = float(input("Enter Score:"))
if score >= 0.9 :
print('A')
elif score >= 0.8 :
print('B')
elif score >= 0.7 :
print('C')
elif score >= 0.6 :
print('D')
el... |
64f3fd5edd95ea1566cf1d9036c25ef6ad0cdbe7 | aahana-khajanchi/python | /pythonPrograms/ex3.py | 931 | 3.984375 | 4 | cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car #120
average_passengers_per_car = passengers / cars_driven #3
print ("There are ", cars, "cars available.")
print ("There are only",(drivers),"drivers ava... |
c2d9efb761f7309d7f46e827f422c62ea75b3632 | aahana-khajanchi/python | /pythonPrograms/lar.py | 1,843 | 3.96875 | 4 | largest = -1
list = [1,9,23,22,18]
for num in list :
if num > largest :
largest = num
print('largets no. is ',largest)
for num in list :
if num > 18 :
print ('students age greater than 18 is',num)
found = False
for num in list :
if num == 18 :
print(num)
fl... |
a49ea695c2a832599cc06336e13b749c962c1e92 | aahana-khajanchi/python | /pythonPrograms/dictionaries.py | 887 | 3.96875 | 4 | # Dictionaries
ddd = dict()
ddd['age'] = 21
ddd['course'] = 182
print(ddd)
ddd['age'] = 23
print(ddd)
# dictionary Literals (Constants)
jjj = {'chuck' : 1 , 'fred' : 42, 'jan' : 100}
print(jjj)
ooo = {} # empty dictionary
print(ooo)
# Counting the words in a dictionary
name = dict()
n... |
0dd4dbbaf047c5e1383eeebb0045861b0d3dd4ae | aahana-khajanchi/python | /pythonPrograms/userInput.py | 470 | 3.9375 | 4 | name = input(' who\tr u? \n')
print ('welcome' , name)
age = input('enter age\n')
print ( 'age\tis\t', int( age))
# converting floor according to US conversion
name = input('which floor\t') # input takes as a string
usf = int (name) + 1 #if u type - usf = int (name + 1) then O/P is Ty... |
bdb4ad158aeda38ada8f2ca88850aab3338393b4 | elrosale/git-intro | /intro-python/part1/hands_on_exercise.py | 1,140 | 4.3125 | 4 | """Intro to Python - Part 1 - Hands-On Exercise."""
import math
import random
# TODO: Write a print statement that displays both the type and value of `pi`
pi = math.pi
print(type(pi), (pi))
# TODO: Write a conditional to print out if `i` is less than or greater than 50
i = random.randint(0, 100)
if i < 50:
... |
3132a0ddd93248c2dd21e26f2615e4c5f0c753b5 | AdamColton/eulerProblems | /Euler3.py | 348 | 3.59375 | 4 | import math
def is_prime(x):
i=2
sqrt_x=math.floor(math.sqrt(x))
while i<=sqrt_x:
if x%i==0:return False
i+=1
return True
N=317584931803
i=math.floor(math.sqrt(N))
found=False
while not found:
if N%i==0:
if is_prime(i):
found=True
break
... |
1fe2bf5f897fb7b4d4779fe61175e5b80198d78b | AdamColton/eulerProblems | /euler27.py | 1,276 | 3.578125 | 4 | from math import sqrt
def functional(func):
def build(*x):
try:
if x not in func.D: #check if value exists in the functions dictionary
func.D[x] = func(*x) #if its not there, calculate
except: #if the function doesn't have a dict... |
75cf0d85b19b582e5f5ac1486125ba74782c9f29 | AdamColton/eulerProblems | /euler65.py | 322 | 3.5625 | 4 | def continuousFractionSieriesForE(x):
for i in xrange(x,1, -1):
if i%3 == 0:
yield i*2 / 3
else:
yield 1
yield 2
def sumOfDigits(x):
return sum([int(i) for i in str(x)])
n=1
d=0
for i in continuousFractionSieriesForE(100):
n,d = i*n+d, n
print sumOfDigits(n)
... |
8e961a2a3f0910aa78e822369a4511bdf4c261b3 | Mahbub-Ferdous/IDE_Study | /setup_pycham.py | 3,643 | 3.609375 | 4 | ## Pycharm is the best IDE for python dev cause its build in for python and the only python . it also allow HTMl, CSS, Javascript, SQl
lets talk about install and setup:
1. Install pycharm in linux(ubuntu) == Go to your termnal and just command ---- sudo snap install pycharm-community --classic
simply its t... |
277001f219bf21982133779920f98e4b77ca9ec0 | DeLucasso/WePython | /100 days of Python/Day3_Leap_Year.py | 465 | 4.3125 | 4 | year = int(input("Which year do you want to check? "))
# A Leap Year must be divisible by four. But Leap Years don't happen every four years … there is an exception.
#If the year is also divisible by 100, it is not a Leap Year unless it is also divisible by 400.
if year % 4 == 0:
if year % 100 == 0:
if year % 4... |
161d3cdde771bd38133f2855e9ecbfa46f208dc8 | yuuty3223/Trial | /while.py | 444 | 3.984375 | 4 | some_list = [1, 2, 3, 4, 5]
#i = 0
#while i < len(some_list):
# print(some_list[i])
#
#
#for i in some_list:
# print(i)
#for s in 'abcde':
# print(s)
#
#for word in ['My','Name', 'is', 'Mike']:
# if word == 'Name':
# continue
# #break
# print(word)
for fruit in ['apple', 'banana', 'oran... |
128c95a3d794216643e1a2d7a573dbfd70104685 | warManHy/python_medium | /2-6.py | 1,012 | 3.75 | 4 | # coding: utf-8
"""
用户的历史记录功能
"""
from random import randint
from collections import deque
# d = deque([], 5)
# d.append(1)
# d.append(2)
# d.append(3)
# d.append(4)
# d.append(5)
# print d
# d.append(6)
# print d
N = randint(0, 100)
import pickle
# 将对象存在文件
# pick.dump(q, open("hi"), 'w')
# pick.... |
fcdd087b9eb04ece96984a4c1d0d231ab5ee1467 | yhoazk/cloaked-octo-computing-machine | /pickle_ex/basic_ex/pickle_ex.py | 642 | 3.5625 | 4 | #!/usr/bin/python
"""
Example of the library pickle to store
python objects and restore them again
w/o processing them
"""
import pickle
import numpy as np
"""
Define objects to store
"""
npTest_obj = np.asarray([[1,2,3],[6,5,4],[8,7,9]])
strTest_obj = "pickle example XXXX"
if __name__ == "__main__":
# st... |
faadc9e1f7dff707162f555aa474582b1bc31c1c | JLBR/School-Projects | /Linux-C-Python/Linux-Python-Examples/Dynamic-Progamming-Primes.py | 720 | 4.0625 | 4 | import sys
def primes(a):
if a == 1:
print "The first prime is 1"
return()
elif a == 2:
print "The second prime is 2"
return()
elif a == 3:
print "The third prime is 3"
return()
primelist = [3]
primeindex = 5
while (len(primelist)+2) != a:
notprime = 0
for prime in primelist... |
eafb1504b044f979b448d1bb1b7b0065df052721 | n-apier/CC-CS-PRACT | /Code_Challenges/strings.py | 4,051 | 4.09375 | 4 | letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
# Write your unique_english_letters function here:
def unique_english_letters(word):
uniques = 0
for letter in letters:
if letter in word:
uniques += 1
return uniques
# Uncomment these function calls to test your function:
print(u... |
7fafc06603e1fc89d55b8dc1bcda605ef5449776 | n-apier/CC-CS-PRACT | /Code_Challenges/functions.py | 3,092 | 4.03125 | 4 | # Write your tenth_power function here:
def tenth_power(num):
return num ** 10
# Uncomment these function calls to test your tenth_power function:
print(tenth_power(1))
# 1 to the 10th power is 1
print(tenth_power(0))
# 0 to the 10th power is 0
print(tenth_power(2))
# 2 to the 10th power is 1024
# Write y... |
7951769cb57636d52815e1f3880db97669706c73 | arujit/ImageCompressor | /Server.py | 4,879 | 3.546875 | 4 | """
author:james.bondu
TO-DO
- Use multi Threading for handling of server sending thing ( A separate method to receive images)
Doing
- Multi Threading to both send and receive data
- There must be some way to simply check if its sending or receiving...May be try a separate thread(or main thread )to do the checking f... |
435f96309f8dbcc0ebf5de61390aae7f06d4d7e9 | ashwin1321/Python-Basics | /exercise2.py | 1,541 | 4.34375 | 4 | ##### FAULTY CALCULATOR #####
def calculetor():
print("\nWellcome to Calc:")
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
** for power
% for modulo
Enter... |
2cf09eb1c34ba8ebe3a12def9cc1bb7fc25a1450 | ashwin1321/Python-Basics | /oops7.single inheritance.py | 1,535 | 4.03125 | 4 | # We can access all the function in the parent class and also add the needed function in the child class
class Employee:
no_of_leaves = 8
def __init__(self, aname, asalary, arole, languages):
self.name = aname
self.salary = asalary
self.role = arole
self.language = la... |
1b022a05c38b11750eeb5bc824ea2968628533a5 | ashwin1321/Python-Basics | /lists and its function.py | 1,724 | 4.625 | 5 |
########## LISTS #######
# list is mutable, we can replace the items in the lists
'''
grocery = [ 'harpic', ' vim bar', 'deodrant', 'bhindi',54] # we can include stirng and integer together in a list
print(grocery)
print(grocery[2])
'''
'''
numbers = [12,4,55,16,7] # list can also be... |
f203639ca969c98bc2847dc3c78e40e5b82c2747 | ashwin1321/Python-Basics | /more on files,seek(),tell().py | 423 | 3.8125 | 4 | f = open("qwerty.txt")
'''
print(f.tell()) # prints where the index is, gives out its value
print(f.readline()) # prints the first line in the file
print(f.tell())
print(f.readline())
'''
f.seek(0) # f.seek(... |
c9a906c09b5154e351855e681a01c30f53c0428e | ashwin1321/Python-Basics | /file,withblock.py | 325 | 4 | 4 | with open('qwerty.txt') as f: # works same as the file pointer below f, here we dont need to close the file
print(f.read(4))
# f = open("qwerty.txt",'rt') # "rt" mode is default, doesnot matter if we write or not
# # print(f.readlines())
# print(f.read(10))
# f.cl... |
53b0a04657a620aaaf20bfee9f8a5b8e9b08e322 | ashwin1321/Python-Basics | /oops10.public, protected and private.py | 1,231 | 4.125 | 4 | class Employee:
no_of_leaves = 8 # This is a public variable having access for everybody inside a class
var = 8
_protec = 9 # we write a protected variable by writing "_" before a variable name. Its accessi... |
682fe696fafb0ed15f40e95bec558e4d6e2d68c4 | spidernik84/udemypybootcamp | /tictactoe_v1.py | 1,711 | 3.734375 | 4 |
tabledict = { '1': '1', '2': '2', '3': '3',
'4': '4', '5': '5', '6': '6',
'7': '7', '8': '8', '9': '9' }
winner = False
current_player = 1
turn = 0
def print_board():
print('{} | {} | {}'.format(tabledict['1'],tabledict['2'],tabledict['3']))
print('---------')
print('{} | {} |... |
3ea53c632270382bb79acb5b92330d3feb8ee02f | salvat06/Professional-Portfolio_WIP | /Assignment_02_JamesSalvatore.py | 7,873 | 3.796875 | 4 | #-------------------------------------------------------------------------------
# Name: Rowan Zombie Text Adventure
# Purpose:
#
# Author: Owner
#
# Created: 20/02/2014
# Copyright: (c) Owner 2014
# Licence: <your licence>
#----------------------------------------------------------------... |
f3841232fa3b036b250b32c7cdb578c6ad43f1f1 | NiamhMurray/NMurray | /MTMG06_Assingment1_25821522.py | 9,029 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 29 17:22:01 2020
@author: niamhmurray
"""
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as sps
from scipy.special import comb
def read_in_data(filename):
"""
readindata reads in numerical data from a txt file and pro... |
42e95062e5f04bc6b21a80b39ca93c0949b09183 | AnkitaPisal1510/assignemt_repository | /pythonpart1.py | 224 | 3.90625 | 4 | user_input=int(input("enter a number:-"))
index1=1
print("")
while index1<=user_input:
print(" ---"*user_input)
print(f"| {0} "*user_input+"|")
index1+=1
if index1==user_input+1:
print(" ---"*user_input)
|
23ce2ae2932356cca15beceb41418d7c2e25304b | sferbrb/LaserSLAM | /新人培训/陈俊威/答案/text5.py | 340 | 3.9375 | 4 | #题目5:一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过
#多少米?第10次反弹多高?
sum=0
height=100
for i in range(1,11):
sum=sum+height
height=height/2
print('共经过',sum,'米')
print('第十次反弹',height,'米') |
0522d27f7feef7eee6830d2dee89007a2a131bc4 | sferbrb/LaserSLAM | /新人培训/吴英俊/答案/text88.py | 303 | 3.59375 | 4 | #读取7个数(1—50)的整数值,每读取一个值,程序打印出该值个数的*。
#加入了我自己的元素:不用输入而是随机读取 使用了延迟函数
import random
import time
n=1
while n<=7:
x=random.randint(1,50)
print('*'*x+' x is %d.'%x)
n+=1
time.sleep(1) |
3ddbca242c693d240ddab5550f8260965fec397c | sferbrb/LaserSLAM | /新人培训/吴英俊/答案/text62.py | 77 | 3.515625 | 4 | #find函数查找字符串。
str1='abcdefg'
str2='de'
print(str1.find(str2)) |
08ed00c9059fa45c0ff04fcce94a4aa6e9d660a5 | sferbrb/LaserSLAM | /新人培训/吴英俊/答案/text1.py | 225 | 3.515625 | 4 | count=0
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if (i!=j) and (j!=k) and (i!=k):
count=count+1
print(i,j,k)
print('个数为',count)
######
## #####asdfghjklasdfasdf |
af2dd436ff312dedc60d3008027a3a36db05a85f | sferbrb/LaserSLAM | /新人培训/陈俊威/答案/text11.py | 198 | 3.859375 | 4 | #题目11:斐波那契数列。
if __name__=='__main__':
def fib(n):
a=1
b=1
if n==1 or n==2:
return 1
else:
return fib(n-1)+fib(n-2)
for i in range(1,11):
print(fib(i)) |
ca723b64779e3c5018fdb9603bc4d54873e35a50 | sferbrb/LaserSLAM | /新人培训/吴英俊/答案/text39.py | 716 | 3.5625 | 4 | #有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。
#改一下题目,下面是我自己的一些想法:首先用户输入随机数,输入-1结束,然后排序
#5.30 有一点错误 明日改
L=[]
L1=[]
again=1
while again:
n=int(input("Please enter a number:"))
if n==-1:
again=-1
break
else:
again=1
L.append(n)
L.sort()
print(L)
x=int(input("Please enter another one number"))
if(x>L[len(L)-1]... |
cbd1bc19c0a57a5fd67a69303b6deb8fcc1fc279 | jw8957/practice | /BeautyOfProgramming/Zuma/MaximumSameColorInCircle.py | 1,488 | 3.78125 | 4 | def Prev(circle, i):
if circle is None or len(circle) == 0:
return -1
if i > 0:
return i - 1
else:
return len(circle) - 1
def Next(circle, i):
if circle is None or len(circle) == 0:
return -1
if i == (len(circle) - 1):
return 0
else:
ret... |
18674e84211b968d3129b7c0ce1bef208dbffab8 | tiankonghenlan20113046/Networkx | /Tutorial_Networkx.py | 1,222 | 3.53125 | 4 | import networkx as nx
nx.to_networkx_graph()
nx.draw_networkx_edge_labels()
nx.draw_networkx_labels()
G = nx.Graph()
nx.draw()
print("G.degree:"+str(G.degree))
G.add_node(1) #添加一个节点
print("G.degree:"+str(G.degree))
G.add_nodes_from([2,3])#add node list
print("G.degree:"+str(G.degree))
H = nx.path_graph(20)#线性连接点的路径图
p... |
80e284872663bb1c8ff9a8cfe12ef4edf9b8c27f | thisisedyip/D08 | /HW08_ch11_ex02d.py | 2,707 | 3.734375 | 4 | #!/usr/bin/env python3
# HW08_ch11_ex02d.py
# (1) Write a more concise version of invert_dict_old.
# (2) Paste in your completed functions from HW08_ch11_ex02a.py
# (3) Update print_hist_new from HW08_ch11_ex02b.py to be able to print
# a sorted version of the dict (print key/value pairs from 0 through the
# largest ... |
50efaf2f7e88e9bfee1437a8cdc9159040ec1818 | jvansch1/Data-Science-Class | /pandas/operations.py | 1,210 | 3.546875 | 4 | import numpy as np
import pandas as pd
df = pd.DataFrame({
"col1": [1, 2, 3, 4],
"col2": [444, 555, 666, 444],
"col3": ["abc", "def", "ghi", "xyz"]
})
# unique values
unique_in_column = df["col2"].unique()
print(unique_in_column)
# unique and occurences
occurences = df["col2"].value_counts()
print(occu... |
0209c76a48557122b10eaedbac5667641078a631 | jvansch1/Data-Science-Class | /NumPy/conditional_selection.py | 292 | 4.125 | 4 | import numpy as np
arr = np.arange(0,11)
# see which elements are greater than 5
bool_array = arr > 5
#use returned array of booleans to select elements from original array
print(arr[bool_array])
#shorthand
print(arr[arr > 5])
arr_2d = np.arange(50).reshape(5,10)
print(arr_2d[2:, 6:)
|
dc914377bfebde9b6f5a4e2b942897d4cd2a8e25 | lilimehedyn/Small-projects | /dictionary_practice.py | 1,082 | 4.125 | 4 | #create a dict
study_hard = {'course': 'PythonDev', 'period': 'The first month', 'topics': ['Linux', 'Git', 'Databases','Tests', 'OOP'] }
# add new item
study_hard['tasks'] = ['homework', 'practice online on w3resourse', 'read about generators', 'pull requests',
'peer-review', 'status', 'feedbac... |
c501974818702aad8bcc4bf5c11708c1f3e19c19 | Vagacoder/LeetCode | /Python/String/Q0028_ImplementStrStr.py | 1,377 | 3.875 | 4 | #
# * 28. Implement strStr()
# * Easy
# * Implement strStr().
# Return the index of the first occurrence of needle in haystack, or -1 if needle
# is not part of haystack.
# Clarification:
# What should we return when needle is an empty string? This is a great question
# to ask during an interview.
# For the pur... |
55868aa5ef60703249ebae0e1e6050d46c82cfbe | Vagacoder/LeetCode | /Python/Q0014ext1_Trie.py | 5,141 | 3.921875 | 4 | # Q14. Extension 1, Trie
# Practice
R = 26
class TrieNode:
def __init__(self):
self.children = [None] * R
self.value = ""
self.isEndOfWord = False
def isEndNode(self) -> bool:
for child in self.children:
if child != None:
return False
retur... |
6fda601b55e03f5904f4824fb5e8fa94d69d5ea2 | Vagacoder/LeetCode | /Python/DynamicProgram/Q0516_LongestPalidrome.py | 2,197 | 3.65625 | 4 | #
# * 516. Longest Palindromic Subsequence
# * Medium
# * Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.
# * Example 1:
# Input: "bbbab"
# Output: 4
# One possible longest palindromic subsequence is "bbbb".
# * Example 2:
# Input: "cb... |
96d67d02dae313352f9d89f04a517b1f6b935519 | Vagacoder/LeetCode | /Python/LinkedList/Q0141_LinkedListCycle.py | 2,980 | 4 | 4 | #
# * 141. Linked List Cycle
# * Easy
# * Given head, the head of a linked list, determine if the linked list has a cycle in it.
# There is a cycle in a linked list if there is some node in the list that can be
# reached again by continuously following the next pointer. Internally, pos is
# used to denote the index... |
056dd343cf0b1b96b01c62a161b826a73b51f408 | Vagacoder/LeetCode | /Python/Tree/Q0105_ContructBTreeFromPreInOrder.py | 3,293 | 3.84375 | 4 | #
# * 105. Construct Binary Tree from Preorder and Inorder Traversal
# * Medium
# * Given preorder and inorder traversal of a tree, construct the binary tree.
# * Note: You may assume that duplicates do not exist in the tree.
# * For example, given
# preorder = [3,9,20,15,7]
# inorder = [9,3,15,20,7]
# * Return th... |
3f5b52b70c56b3c4d76d41519763bacdde27c23e | Vagacoder/LeetCode | /Python/DynamicProgram/Q0714_BestTimeBuySellStockFee.py | 2,408 | 3.796875 | 4 | #
# * 714. Best Time to Buy and Sell Stock with Transaction Fee
# * Medium
# * Your are given an array of integers prices, for which the i-th element is the
# * price of a given stock on day i; and a non-negative integer fee representing
# * a transaction fee.
# * You may complete as many transactions as you like, ... |
97dce44d9bdd9dfad2fd37f8e79d5956f6c64bd0 | Vagacoder/LeetCode | /Python/DynamicProgram/Q0122_BestTimeBuySellStock2.py | 2,454 | 4.15625 | 4 | #
# * 122. Best Time to Buy and Sell Stock II
# * Easy
# * Say you have an array prices for which the ith element is the price of a given
# * stock on day i.
# * Design an algorithm to find the maximum profit. You may complete as many
# * transactions as you like (i.e., buy one and sell one share of the stock multi... |
fafd3554dae7a49f16598b2269ee1086d7df2786 | Vagacoder/LeetCode | /Python/Interval/Q0986_IntervalListIntersections.py | 1,463 | 3.703125 | 4 | #
# * 986. Interval List Intersections
# * Medium
# * Given two lists of closed intervals, each list of intervals is pairwise disjoint
# * and in sorted order.
# * Return the intersection of these two interval lists.
# * (Formally, a closed interval [a, b] (with a <= b) denotes the set of real
# * numbers x with a... |
6396751b5e099078737ff179113ceda89fbce28c | dishashetty5/Python-for-Everybody-Functions | /chap4 7.py | 743 | 4.40625 | 4 | """Rewrite the grade program from the previous chapter using
a function called computegrade that takes a score as its parameter and
returns a grade as a string.
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F"""
score=float(input("enter the score:"))
def computegrade(score):
try:
if(scor... |
b75eaa4925bb7842354e6bb1797c64edee765313 | Juano45/Python | /love_calculator.py | 915 | 4.09375 | 4 | # 🚨 Don't change the code below 👇
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
count1 = 0
count2 = 0
combined_name = name1 + name2
lower_name = combined_name.lower()
t =... |
3ad3606cb2a8a2127d3c764a780042cbbc729a81 | JeanPaiva42/recommendaJogos | /recommendaJogos/Usuario.py | 883 | 3.640625 | 4 | class Usuario(object):
def __init__(self, nome):
self._nome = nome
self._listaJogos = {}
self._somaPref = []
def getNome(self):
return self._nome
def adicionaJogo(self, nome, nota):
self._listaJogos[nome.upper()] = nota
def removeJogo(self, nome):
d... |
8312e86fe138e250ce7992e65904f8b44d3d7d3e | ChiaGolin/Thesis | /SmartDirection_BEACON/DISPLAY.py | 4,057 | 3.5625 | 4 | #!/usr/bin/env python
import pygame
import keyboard
class DisplayArrow:
def __init__(self, arrow_display, wait, display_Ready_q):
self.arrow_display=arrow_display
self.wait=wait
self.display_Ready_q=display_Ready_q
def Go(self):
################# PYGAME SETTING #############
... |
fd4c277d2b77fc2117955c71667fd3d68f7e2554 | joe199/beer-coholic | /database/beer_quantity.py | 2,105 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy_declarative import User, Base
import sqlite3
class beer_quantity(object):
"""DataBase of quantity beer served class"""
def __init__(self):
super(beer_quantity, sel... |
e6452955f72f873e31c18bd865b46b8e07bdf21d | spruceb/strk | /utilities.py | 475 | 3.53125 | 4 | def binary_groupby(iterator, key):
"""Return the iterator split based on a boolean 'streak' function"""
iterator = iter(iterator)
last_item = next(iterator)
result_list = [last_item]
for item in iterator:
if key(last_item, item):
result_list.append(item)
else:
... |
08de98547c3bd1f48944e321e9abaece43563aa9 | nurur/GeneralProgramming | /TernaryOperator.py | 265 | 4.28125 | 4 | # Ternary Operator in Python
# Rule: a if testCondition else b
x=1; y=2; z=4
print 'x, y, z values are ', x, y, z
print ' '
m = x if (x<y) else z
print 'Ternary operator result:', m
n = x if (x>y) else z
print 'Ternary operator result:', n
|
dfe1b71f4bca7dc0438ae83fd418ad131fb8aba9 | huzaifahshamim/coding-practice-problems | /Lists, Arrays, and Strings Problems/1.3-URLify.py | 1,061 | 4.1875 | 4 | """
Write a method to replace all spaces in a string with '%20'. You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true"
length of the string. (Note: if implementing in Java, please use a character array so that you can
perform this operation i... |
a4cddef8d539dd0fea40b0c7b472681fc26d101b | Hkadro/CopsAndRobbers | /Controlled_Cops_and_Robbers_Complete_Graph.py | 2,967 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 8 16:49:20 2021
@author: Hkadro
"""
#CSCI 39575 Project 1
#This Is A Robber Win Graph
#Controlled Implementation of Cops and Robbers on Connected Graph
#Rule can only move to neighbor nodes or Stay in Place
#Rule only one Person can occupy a single node at a ti... |
52ffce655d6abde5eb94be8ea717ff4df4fa368a | SamyuelDanyo/data-structures | /src/binary_search_tree/python/binary_search_tree.py | 9,469 | 3.890625 | 4 | #!/usr/bin/env python
#################################################
""" binary_search_tree.py
# # Binary Search Tree(BST) Implementation
# Supports:
# - Insert, remove.
# - Size, min, max, height.
# - Recursive traverse:
# > {Pre, in, reverse in, post}-order, level
# - Iterative trave... |
dd6ef3c8c4171fe5b1bac5cf3694003c395d317a | duyetkai2/taplamgit | /student.py | 932 | 4.03125 | 4 | class Student:
def printInfo(self):
print(f"Fullname {self.name}")
st1 =Student()
st1.name="Duyet"
st1.printInfo()
del st1.name
del st1
class Dog:
def __init__(self,name="",age=0):
self.name=name
self.age=age
def say(self):
print(f"GO GO{self.name}")
mydog= Dog()
mydog.say()... |
6a488674fc998c0b8c5c68aa5fb35201d01c9487 | sc4599/LeetCode | /231/__init__.py | 1,403 | 3.828125 | 4 | # coding=utf-8
__author__ = 'songchao'
# 将2的幂次方写成二进制形式后,很容易就会发现有一个特点:二进制中只有一个1,并且1后面跟了n个0;
# 因此问题可以转化为判断1后面是否跟了n个0就可以了。
# 如果将这个数减去1后会发现,仅有的那个1会变为0,而原来的那n个0会变为1;
# 因此将原来的数与去减去1后的数字进行与运算后会发现为零。
# 最快速的方法:
#
# (number & number - 1) == 0
#
# 原因:因为2的N次方换算是二进制为10……0这样的形式(0除外)。与上自己-1... |
7945a84de6c4ade8b799e9d2a1504b9bb2fab0fd | stuartsan/algscourse | /ps6/two_sum.py | 967 | 3.546875 | 4 | import sys
def two_sum(lst, targets):
lookup = set(lst)
yes_count = 0
for target in targets:
for num in lookup:
if target - num is not num and target - num in lookup:
yes_count += 1
break
return yes_count
def tests():
lst = [4, 7, 1, 3, 19]
t... |
36f02234d3d66bf6832f9f48b6325833c826e807 | stuartsan/algscourse | /ps1/inversion_count.py | 1,161 | 3.921875 | 4 | import sys
def sort_and_count(lst):
"""Basically divide and conquer merge sort."""
if len(lst) <= 1:
return (lst, 0)
else:
mid = len(lst) / 2
first_half = lst[:mid]
second_half = lst[mid:]
return merge_and_count_inv(sort_and_count(first_half),
... |
fad120ce8efd980a71088226d3b3c6bd70634dec | LennyBoyatzis/code-wars | /find-the-capitals.py | 176 | 3.875 | 4 | def capitals(word):
return [word.index(letter, index) for index, letter in enumerate(word) if letter.isupper()]
if __name__ == "__main__":
print(capitals("CodEWaRs"))
|
9eb4b4daa7ab82a5261ba6e9aa747e6588a67c10 | LennyBoyatzis/code-wars | /next-bigger-number-with-digits.py | 651 | 3.921875 | 4 | def swap_elements(target_list, i_one, i_two):
target_list[i_one], target_list[i_two] = target_list[i_two], target_list[i_one]
return target_list
def next_bigger(n):
int_list = [int(x) for x in str(n)]
for ind, el in enumerate(int_list):
ind_plus = ind
swapped_list = swap_elements(int_... |
b08b671eab97fae434f7a07aac6cf54b954fd219 | LennyBoyatzis/code-wars | /valid-parentheses.py | 688 | 4 | 4 | import re
def valid_parentheses(string):
clean_str = re.sub(r'[^\(\)]', '', string)
pattern = r'\([^\) ^(]*\)'
balanced_parens = re.search(pattern, clean_str)
while re.search(pattern, clean_str):
clean_str = re.sub(pattern, '', clean_str)
return True if len(clean_str) == 0 else False
# de... |
2da4d2b84d2e76b9f14e50e55fb889f223725c26 | LennyBoyatzis/code-wars | /chain-map.py | 525 | 3.53125 | 4 | from collections import ChainMap
# We can link multiple dictionaries and can be treated as a single unit
# We can use it to store default values and override when required
# We can use it to store configuration with some default values
car_parts = {'hood': 500, 'engine': 5000, 'front_door': 750}
car_options = {'A/C':... |
f07ca81fcdbea87a0381dbe6d60cd897dc282d1d | LennyBoyatzis/code-wars | /duplicate-encoder.py | 1,231 | 3.578125 | 4 | # Because count is being used
# We have a loop within a loop
# This makes it an O(n^2) method
# This method is concise and readable but could be more efficient
# really_long_test_string = ''.join(['a' for x in range(100)])
really_long_test_string = 'adfajshdval;cj.vncv.,ndfa.kds,nfasd.kjfhnad.kcj,ndk.jfhndsk.'
def d... |
9ac9eafc426d04f3cc43bcd5fa1794af825a90cd | Aparna-Sakshi/ORLab | /Lab2/18MA20007_prog_lab2.py | 4,229 | 3.5625 | 4 | import math
from itertools import combinations
# m number of equations
# arr is the coefficient matrix (list of lists)
# e is the error
# b is the value matrix
# z is the coefficients of objective function
# objective is either to minimize or maximize the objective func
e = 0.001
def objective_func(z, ... |
757c6618ccb681701d7b3f0e7111fd2ae4444d81 | earth519/IMAC-trainee | /practicePython/HW7.2.py | 552 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 12 09:09:57 2018
@author: SevenHope
"""
#print ("Please in put the number of row: ")
#n = input('Enter your input')
#n = int (n)
while True:
try:
n = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was not ... |
ab08c2f420983c1953facf8f1a18d5f974f6b5e0 | idep-nter/dungeon-crawler | /objects.py | 2,342 | 3.734375 | 4 | import random
import time
class Shrine:
def __init__(self):
pass
@staticmethod
def heal(player):
"""Sets player's health points to maximum."""
player.currentHealth = player.maxHealth
class Chest:
def __init__(self, potions, items):
self.potions = potions
self... |
e0588a92499fdf8393d8b647d2b993750ec024ae | RyodoTanaka/Coding_The_Matrix | /python/chap_0/0.5.28.py | 120 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def nextInts(L) : return [i+1 for i in L]
L=[1,5,7]
print nextInts(L)
|
6e2974066ca139c6d65b0c7f7264a0b9647de49a | RyodoTanaka/Coding_The_Matrix | /python/chap_1/1.7.6.py | 216 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def myMin(L):
ret=L[0]
for x in L:
if x<ret:
ret=x
return ret
list=[2,4,1,8,5]
print myMin(list)
list=[2,4,1,8,-3,5]
print myMin(list)
|
4e8589ebd2becdfa17015e15a0d85cace91a4dc0 | RyodoTanaka/Coding_The_Matrix | /python/chap_0/0.5.31.py | 201 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def list2dict(L, keylist) : return {keylist[i]:L[i] for i in range(len(keylist))}
L=['A', 'B', 'C']
keylist=['a', 'b', 'c']
print list2dict(L, keylist)
|
8fe1e709b7a3eb632b2d0bd65544e078bdca1beb | RyodoTanaka/Coding_The_Matrix | /python/chap_0/0.8.3.py | 206 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def row(p, n):
return [x+p for x in range(n)]
ret=[row(x,20) for x in range(15)]
print ret
ret=[ [x+y for x in range(20)] for y in range(15) ]
print ret
|
b19c117dd4c6f3b371a20b1f4c0805ea8bed9115 | RyodoTanaka/Coding_The_Matrix | /python/chap_0/0.5.30.py | 198 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def dict2list(dct, keylist) : return [dct[i] for i in keylist]
dct={'a':'A', 'b':'B', 'c':'C'}
keylist=['b', 'c', 'a']
print dict2list(dct, keylist)
|
6fc675f43ea490852e171cb978a9b9442c5f565d | Oscar883/AprendiendoPython | /Concatenacion.py | 443 | 4.1875 | 4 | #Se declaran dos variables con input para ingresar la informacion
#necesaria en este caso nombre y apellido
nombre=input("Nombre:")
apellidos=input("Apellidos:")
#Se concatenan los valores str, junto con la literal " " (para tomar un espacio)
NombreCompleto=nombre+" "+apellidos
#Se asigna a la variable la represe... |
8af1bfd9badb27dd9704a7f82679b785f95f4497 | zaynaib/codeExamples | /Info490_Su14/week6/sqlcensus.py | 3,263 | 3.78125 | 4 | #!/usr/bin/python
# Week 6 Problem 2
# Do not delete the comments.
# Do not chnage the functions names, do not change the input parameters.
# Do not change the return types of the functions.
# Your code goes to the part where it says your code goes here.
# Do not change anything else other than the part where it says ... |
04352e402883d0d9b858bfab2e9fc81addbaa2a6 | yadac/PythonApplication1 | /PythonApplication1/ExceptionSample.py | 289 | 3.6875 | 4 | # exception
try:
x = 10 / 0
except Exception as e:
print(e) # division by zero
else:
# exception does not raise
print("any exceptions had not raised.")
finally:
print("finally fuga") # fuga
try:
raise Exception("hoge")
except Exception as e:
print(e) # hoge
def hogehoge():
pass |
1056f350cd15e803205660fa360d5c0d05790ab6 | Shub1970/heap_short | /heap_short.py | 988 | 3.84375 | 4 | def sub_heap(array, index):
left = 2 * index + 1
right = 2 * index + 2
large = index # initali index is the largest number
if left<len(array) or right<len(array):
if left<len(array) and array[left] > array[index]:
large = left
if right<len(array)and array[right] >... |
d5803627759aa61a4a46fb47f7630eab3b24b89b | maximesalomon/hackerrank | /Python/linear_search.py | 243 | 3.640625 | 4 | lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
def linear_search(lst, num):
i = 0
for l in lst:
if l == num:
return i
else:
i = i + 1
print(linear_search(lst, 19)) |
728430b4cd7f31c81fff5c8a8b805df85a6daf81 | maximesalomon/hackerrank | /Python/insersion_sort.py | 272 | 3.703125 | 4 | lst = [7, 9, 4, 23, 2, 0, 8, 10, 5]
def insertion_sort(lst):
for i in range(1, len(lst)):
j = i - 1
while lst[j] > lst[j + 1] and j >= 0:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
j -= 1
return lst
print(insertion_sort(lst)) |
c44ccf0ec1d38d94787e137d604e245249a8a5bf | Nishan52/project | /practice 5.py | 114 | 4.28125 | 4 | string=input("Please enter your string")
result=string.replace(" is"," was",3)
result=result.upper()
print(result) |
8d3154f857a312ea0beba8935f07ed4dcb6db6c2 | tiddler/fishpond | /LeetCode/07_Reverse Integer.py | 259 | 3.765625 | 4 | class Solution:
# @return an integer
def reverse(self, x):
ans = str(abs(x))[::-1]
if x < 0:
ans = '-' + ans
ans = int(ans)
if (ans >= 2**31) or (ans < -(2**31)):
return 0
return int(ans) |
6782fb23ebebe56bc6e29120b7205290e7c7947c | shayaansaiyed/Python-Sudoku-Solver | /main.py | 1,247 | 3.53125 | 4 | import sudoku9 as s9
import time as t
def printTW(s, end='\n'):
for char in s:
print(char, end='', flush=True)
t.sleep(0.2)
print(end)
def getUserInput():
print()
print("Hello! Welcome to my Sudoku Solver")
t.sleep(1)
print("Please input each line of your Sudoku puzzle, with ... |
b28f6ff08a3dd52821c10a1b291c092170a8f95d | manthanghasadiya/Sorting-basic | /MergeSort.py | 2,366 | 3.640625 | 4 | #*|*Auther : Ghasadi Manthan J*|*
#*|********ID : 201951065********|*
#*|***Codeforces : manghasadi**|*
#*|******Codechef : gmj2703******|*
import time
def merge(array, l, m, r):
n1 = m - l + 1
n2 = r- m
L = [0] * (n1)
R = [0] * (n2)
for i in range(0 , n1):
L[i] = ar... |
2d49547f51874d6ea900675a10cb86a45f1f36b1 | Stewil/Met_image_downloader | /sort.py | 2,576 | 3.75 | 4 | #!/usr/bin/env python3
import csv
import sys
csv.field_size_limit(sys.maxsize)
infile = "MetObjects.csv"
outfile = "sorted.csv"
lines_to_read = 1000
params = [
[8,"Painting","Drawing","Print"], # object name
[3,"True"], #is public doamin
]
outlist = []
def readline():
global infile, ou... |
3d44b0259855b05bfcaeead2ce3cf0d3cfc134c4 | ChristineTsou/GirlsWhoCodeProjects2016 | /all_my_stuff.tar/all_my_stuff/Documents/pygame_template.py | 2,638 | 4.09375 | 4 | """
Pygame base template for opening a window
Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
Explanation video: http://youtu.be/vRB_983kUMc
"""
import pygame
import random
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 2... |
7e4528361a32103d6b4af971ab7137b31712db6f | ChristineTsou/GirlsWhoCodeProjects2016 | /all_my_stuff.tar/all_my_stuff/Documents/shapes2.py | 263 | 3.84375 | 4 | from turtle import *
def draw_square(length):
pendown()
for i in range(4):
forward(length)
right(90)
def draw_triangle(length):
pendown()
for i in range(3):
forward(length)
right(120)
draw_square(50)
penup()
goto(50,50)
pendown()
draw_triangle(50) |
ca15805e5fa88bc7d91557870e1d31bbb5e85883 | sRash84/pyhtons | /fantasyGameInventory.py | 344 | 3.828125 | 4 | inventory = {
'rope':1,
'torch':6,
'gold coin':42,
'dagger':1,
'arrow':12
}
def displayInventory(stuff):
item_total = 0
print("Inventories :")
for key, val in stuff.items():
print( str(val) +"->"+ key)
item_total += val
print('Total items = '+ str(item_total))
disp... |
e294f151d8eaded0356ab30f0cc961a31aff3698 | vishnuvs369/python-tutorials | /inputs.py | 421 | 4.21875 | 4 | # inputs
name = input("Enter your name")
email = input("Enter your email")
print(name , email)
#-------------------------------------------------
num1 = input("Enter the first number") #The input number is in string we need to convert to integer
num2 = input("Enter the second number")
#num1 = int(input("Enter... |
4851893874164fa54ab79e42851faebd17462296 | vishnuvs369/python-tutorials | /recursion.py | 133 | 3.953125 | 4 | #recursion
def recursion(n):
if n <= 1 :
return n
else:
return n + recursion(n-1)
s = recursion(5)
print(s) |
6f942689ea088e6935121f1be6ceb9233a673764 | kgerot/Project-Euler | /Python/1.py | 94 | 3.6875 | 4 | sum = 0
for i in range(3, 1000):
sum += (i if (i % 3 == 0 or i % 5 == 0) else 0)
print(sum)
|
3b45cb9355386ad44af4f389d19f1850ff7116d7 | rwakulszowa/Skater_pygame | /skater/gameboard.py | 2,061 | 3.546875 | 4 |
class GameBoard:
# infinities to avoid crashes on empty sequence computations
MIN_POSITION = -2 ** 31
MAX_POSITION = 2 ** 31
def __init__(self, obstacles):
self.obstacles = obstacles
def obstacles_under(self, player):
"""
All the obstacles currently positioned under the pl... |
4b36bcb4adedce93cd66f51a6f1b6beace644f5a | merry-hyelyn/Programmers_CodingTest_practice | /k진수에서_소수_개수.py | 526 | 3.65625 | 4 | import math
def convert_number(n, k):
res = ''
while n > 0:
n, mod = divmod(n, k)
res += str(mod)
return res[::-1]
def is_prime(num):
if num == 1:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
... |
0bddc508ce2a5079507fdd0dbe4f55a0c09a2ef7 | Joezeo/codes-repo | /python-pro/io_prac.py | 508 | 4.15625 | 4 | forbideen = ('!', ',', '.', ';', '/', '?', ' ')
def remove_forbideen(text):
text = text.lower()
for ch in text:
if ch in forbideen:
text = text.replace(ch, '')
return text
def reverse(text):
return text[::-1]# 反转字符串
def is_palindrome(text):
return text == reverse(text)
in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.