blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
394d74a1b74264a9326005b4df0e41a7a7baeb8c | sekR4/ML_SageMaker_Studies | /Project_Plagiarism_Detection/helpers.py | 8,199 | 3.53125 | 4 | import operator
import re
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
# Add 'datatype' column that indicates if the record is original wiki answer as 0, training data 1, test data 2, onto
# the dataframe - uses stratified random sampling (with seed) to sample by ... |
57943b92c083b740e40dba6a555c41aae242da39 | mollinaca/ac | /code/speedrun_001/3.py | 200 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
n = int(input())
a = list(map(int,input().split()))
for i in range(len(a)):
print (a[i], end="")
if not i+1 == len(a):
print (",",end="") |
af4c5f576a243d64a4ac69bb1acc0dd7a6915380 | alicevillar/python-lab-challenges | /functions/functions_exercise2.py | 1,487 | 4.34375 | 4 |
####################################################################################################################
# Functions - Lab Exercise 2
#
# Write a function called odds_or_evens that takes a boolean and a list of integers as parameters.
# If the boolean parameter is True, ... |
5a3826655c4f936cf3eead4f40c6539cea9d332a | VinodMeganathan/Guvi | /Print_Minimum_And_Maximum_In_A_List.py | 134 | 4.09375 | 4 | ''' PROGRAM TO PRINT MINIMUM AN MAXIMUM IN A GIVEN ELEMENTS '''
a=int(input())
istring=input()
b=istring.split()
print(min(b),max(b))
|
9b95a9819a47e6e8836f80ecd1f2f1c10b5ce7c5 | sithon512/oop-microbial-growth | /petri.py | 5,459 | 4.0625 | 4 | """
The classes contained in this module define a petri dish instance.
"""
from microbe import Microbe
from nutrient import Nutrient
class PetriCell:
"""
This class defines a cell in the grid that makes up the petri dish. Cells
are acrive classes that handle the interaction between nutrients and
microbes.
"""
... |
7249574ddce16f7586b80bf51dc3412196a31ff4 | techkids-c4e/c4e5 | /Ha Tran/buoi 2_19.6/ve hinh.py | 267 | 3.875 | 4 | from turtle import*
color('black','white')
for side in range(7,2,-1):
if (side%2==0):
color("blue","green")
else:
color("red","yellow")
begin_fill()
for i in range(side):
forward(100)
left(360/side)
end_fill()
|
736cf50cfb5a1ba835e8fb17d6f7759335ad93cd | MONICA-Project/sfn | /WP5/KU/SharedResources/get_incrementer.py | 1,056 | 4 | 4 | # get_incrementer.py
"""Helper function to create counter strings with a set length throughout."""
__version__ = '0.2'
__author__ = 'Rob Dupre (KU)'
def get_incrementer(num, num_digits):
if num >= 10**num_digits:
print('NUMBER IS LARGER THAN THE MAX POSSIBLE BASED ON num_digits')
return -1
els... |
91ebc537033942c138162609c3cf34bfac8f2230 | sindusistla/Algorithms-and-Datastructures | /Algorithms/Brackets.py | 3,511 | 3.578125 | 4 | def CheckTheExpression(expression,exp_len):
retVal=False
for i in range (0,int(exp_len/2)):
#print(expression[i],expression[exp_len-i-1])
if (expression[i] == "{" and expression[exp_len-i-1] =="}" ):
retVal = True
elif(expression[i] == "[" and expression[exp_len-i-1] =="]"):
... |
71f945453045440650923fc513112259bfc9ab8a | craghack55/HackerRank | /Python Track/Strings/FindString.py | 138 | 3.9375 | 4 | #!/bin/python
import sys
import re
def count_substring(string, sub_string):
return len(re.findall("(?=" + sub_string + ")", string)) |
9db938e3ee51d18deb92c117c5a0c8b7e28ab16a | Azjargal13/python-scripts-fun | /problems/mergetools.py | 405 | 3.59375 | 4 | def mergeTool(string, k):
n = len(string)
r = n//k
for i in range(r):
subs = string[:k]
string = string.replace(subs,'')
d=removeSame(subs)
print(''.join(str(key) for key in d.keys()))
def removeSame(substring):
dict_={}
for i in range(len(substring)):
... |
bf366aa9e88861aadca1be85b351870bac3d3d16 | debugu/python | /算法/打印字符串里的所有排列.py | 1,805 | 4 | 4 | import copy
def string_to_list(string):
ls = []
for char in string:
ls.append(char)
return ls
def add_char_to_er_list(newchar, ls): # 向二维数组中插入数据
newls = []
for i in range(0, len(ls) + 1):
temp = copy.deepcopy(ls) # 使用 a[:], list(a),
# a*1, copy.copy(a)四种方式复制列表
#... |
aded92486c519a2c2891201d02301da382713bc9 | samuelveigarangel/CursoemVideo | /ex14_ConversorTemp.py | 123 | 3.859375 | 4 | c = float(input('Digite a temperatura em Celsius: '))
print(f'Temp em celsius {c} convertida para fahrenheit {(c*1.8)+32}') |
1cabd8fe3c1e030ec1f35fb29efa13b18395a102 | soicem/favorite-things-update-check | /database/db.py | 1,598 | 3.5 | 4 | import sqlite3
import time
class dbConnection:
def __init__(self):
self.datatimeFormat = "%04d-%02d-%02d %02d:%02d:%02d"
def insertIntoFavoriteUpdate(self, name, url):
with sqlite3.connect("test.db") as conn:
now = time.localtime()
s = self.datatimeFormat % (now.tm_yea... |
8c200faf14e77b05b96b7ba292b43c53cdfdccd0 | mBortell88/PRG105 | /MobileServicePlanBill.py | 1,792 | 4.15625 | 4 | # Write program that calculates the customer's monthly bill.
# Ask which package the customer has purchased and how many minutes were used.
# Display the total amount due. Use a dollar sign and two decimal places for currency.
# Variables
package_plan = input('Which package are you subscribed to: Package A, Packa... |
bc770e7fe8f4e67a519eb0192dc87af9b7c86370 | MrLao9038/GuessMyPass | /GuessMyPass.py | 2,015 | 3.890625 | 4 | #!/usr/bin/env python3 #Select interpreter for BASH
import random #Module for generating pseudo-random number
print(" ")
print("Let me Guess The Password You")
print("--------------------------------") #Ascii Art
print("8eeee8 8 8 8eeee 8eeee8 8eeee8")
print("... |
21f3f838995f574f198202768c78ad9bd915256e | webturing/PythonProgramming_20DS123 | /lec03-branch2/while.py | 76 | 3.65625 | 4 | print("hello1")
if 4>3:
print("hello2")
while True:
print("hello3")
|
aebde83399de1778a236d51c75ccae3ce1900edf | StevenM42/cp1404practicals | /prac_03/gopher_population_simulator.py | 712 | 4.0625 | 4 | """
CP1404/CP5632 - Practical
Gopher Population Simulator using random number generation
"""
import random
population = 1000
total_years = 10
current_year = 0
min_birth_rate = 10
max_birth_rate = 20
min_death_rate = 5
max_death_rate = 25
print('Welcome to the Gopher Population Simulator!')
while total_years > curren... |
7f77522cc445d6d3fcbb7b8a373f14477a7409fa | imamol555/Machine-Learning | /DecisionTree_SKLearn_Fruits .py | 1,004 | 4.1875 | 4 | #===================================================
#Title : Decision Tree Classifier for classifying a type of fruit
#Author : Amol Patil
#
#=======================================
#classes - Apple and Orange
#Features = [weight, texture]
#Texture- Smooth =1
# Bumpy =0
#Labels - Apple =0
# ... |
d47e7c7a1985bb91c26256b654a0d99ce748f7de | mschae94/Python | /Day18/GUIEx07.py | 582 | 4 | 4 | #라디오 버튼(radio button)
#라디오 버튼은 단 1개의 학목만 선택할 수있다.
from tkinter import *
root = Tk()
root.title("설문조사")
select = IntVar()
select.set(1)
language = [("Pythoin" , 1) , ("Java" , 2) , ("C" , 3)]
def showChoice():
print(select.get())
Label(root , text = "원하는 언어를 선택하세요 :" , justify =LEFT).pack()
#반복처리
for tx... |
3111a5b8d4b0702387db2accefe10c68259a02e0 | SrinuBalireddy/Python_Snippets | /Programs/may/csv_json.py | 586 | 3.5 | 4 | # Write your code here :-)
import csv
#outputFile = open('example1.csv', 'w', newline='')
outputFile = open('example1.csv', 'w')
outputWriter = csv.writer(outputFile)
outputWriter.writerow(['spam','eggs','news','heros'])
outputWriter.writerow(['Hello,world','eggs','news','heros'])
outputWriter.writerow(['10','11','12'... |
af04db972c0e1c6a7d379329becb9127ac7c1933 | tagsBag/tdx_data_server | /tcp_client.py | 2,979 | 3.5 | 4 | from socket import *
def main():
# 1.创建tcp_client_socket 套接字对象
tcp_client_socket = socket(AF_INET,SOCK_STREAM)
# 作为客户端,主动连接服务器较多,一般不需要绑定端口
# 2.连接服务器
tcp_client_socket.connect(("127.0.0.1",54572))
while True:
"""无限循环可以实现无限聊天"""
# 3.向服务器发送数据
# 代码 ... |
df0977f67c970225864736848ed175ae190364dc | ZainebPenwala/Python-practice-problems | /list.py | 248 | 3.828125 | 4 | # sum of all elements in a list
li=[1,2,3,4,5,6,7,8,9]
t=0
for elem in li:
t=t+elem
print(t)
# sum of all individual digits from a list of integer
li=[11,12,13,14,15]
t=0
for elem in li:
for i in str(elem):
t+= int(i)
print(t)
|
6000816670eb88623b6bbd12a90690dde8e82537 | goldan/machinery | /common/utils.py | 3,502 | 4.0625 | 4 | """Common utility functions and constants used throughout the project."""
import collections
import csv
from datetime import datetime
def roundto(value, digits=3):
"""Round value to specified number of digits.
Args:
value: value to round.
digits: number of digits to round to.
Returns:
... |
1c53663a06956393970bdf559415c2dde3fa8576 | Zappp/ADS | /Euclid's algorithm.py | 273 | 3.625 | 4 | import math
def euclid_algorithm(a, b):
if b == 0:
return a, 1, 0
else:
d, x, y = euclid_algorithm(b, a % b)
d, x, y = d, y, x - math.floor(a // b) * y
return d, x, y
d, x, y = euclid_algorithm(35, 50)
print(x)
print(y)
print(d)
|
7a534ee72ca231860ab6ae0e6000d822f0354d5f | luisfeldma/python-study | /felipe14.py | 197 | 3.8125 | 4 | t1 = int(input("Digite o primeiro termo de uma PA: "))
razão = int(input("Digite a razão dessa PA: "))
for c in range(t1, (t1 + (10 * razão)), razão):
print(c, end=" -> ")
print("Acabou!") |
b29b954ef68f983fe37967283a5cb461a8ad6b10 | Hasil-Sharma/Spoj | /primes.py | 1,756 | 4 | 4 | def pow(base, exponent, mod):
"""\
Modular exponentiation through binary decomposition.
We use the same technique as for the binary exponentiation above in
order to find the modulo of our very large exponent and an arbitrary
integer mod.
"""
exponent = bin(exponent)[2:][::-1]
x = 1
... |
4fff70f6d083889fb8e4f75366bd0825e5b45988 | sunshineatnoon/LeetCode | /500KeyboardRow.py | 1,906 | 3.65625 | 4 | ############################## Native Solution #########################
# using dict to check if every character in a word maps to the same number #
# Time taken: 39 ms/77.38%
############################################################################
class Solution(object):
def findWords(self, words):
... |
f24e893b489b21f5f776aaf2eb14328b14f33550 | qaqmander/AITMCLab | /lab2/lab2.py | 3,750 | 4.1875 | 4 | # Welcome to lab2, let's go through some grammars in python2
# We use keyword 'assert' to check something
assert 1 == 1 # Nothing happened
# assert 1 == 2 # program will exits when executing this line
# You have a string, remember to use '\' to escape special character
a = 'I\'m a string' # or a = "I'm a string... |
a5a360e0f8169d621b970af944331b747aef24c5 | bi0morph/automate-the-boring-stuff-with-python | /chapter10.debugging/coinToss.py | 930 | 3.671875 | 4 | #! /usr/bin/env python3
import random
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.debug('Start program')
guess = ''
while guess not in ('heads', 'tails'):
print('Guess the coin toss! Enter heads or tails:')
guess = input()
logging.de... |
54003d9d265479162f8ca5e37da7ca7b84904158 | 1huangjiehua/ArithmeticPracticalTraining | /201826404105黄杰华算法实训/任务一(二分查找(循环)).py | 1,007 | 3.59375 | 4 |
def erfenfa(lis, nun):
left = 0
right = len(lis) - 1
while left <= right: #循环条件
mid = (left + right) // 2 #获取中间位置,数字的索引(序列前提是有序的)
if num < lis[mid]: #如果查询数字比中间数字小,那就去二分后的左边找,
right = mid - 1 #来到左边后,需要将右变的边界换为mid-1
elif num > lis[mid]: #如果查询数字比中间数字大,那么去二分后的右边找
... |
b15b9468b254019ddec88617f0071649634921a1 | abdelrahman-wael/LeetCode-30-DaysChallenge | /week 1/day 7/Determine if String Halves Are Alike.py | 370 | 3.59375 | 4 | class Solution:
def halvesAreAlike(self, s: str) -> bool:
vowels = {'a':0, 'e':0, 'i':0, 'o':0, 'u':0, 'A':0, 'E':0, 'I':0, 'O':0, 'U':0}
mid =len(s)//2
equal = 0
for i in range(mid):
if s[i] in vowels:
equal += 1
if s[i+mid] in vowels:
... |
fca0875e68a5ddf3d0ffcb6e1603efb7dafa6315 | aizhansapina/BFDjango | /week1/informatics/For loop/CFc.py | 122 | 3.96875 | 4 | import math
a = int(input())
b = int(input())
for num in range (a, int(math.sqrt(b)) + 1):
print(num * num, end = " ")
|
8422ba401258dc2ae6e48d755120bdebea442d75 | chongliw/algorithm_py | /fun/mostfrequentchar.py | 542 | 3.984375 | 4 | def most_freq(str, n):
dict = {}
punc = [' ', ',', '.', '-', '?', ';' , ':']
for char in str:
if not char in punc:
if char in dict:
dict[char] += 1
else:
dict[char] = 1
keys = []
for key in dict:
if dict[key] >= n:
k... |
baf5eca94e8e5c3ea23f673d1732ef219de97852 | arunachalamev/PythonProgramming | /Algorithms/LeetCode/L1233removeSubFolders.py | 1,053 | 3.5 | 4 |
# Version 1
def removeSubfolders1(folder):
folder.sort()
res = [folder[0]]
prev_folder = folder[0]
prev_folder_slash = prev_folder +'/'
prev_folder_n = len(prev_folder_slash)
for i in range (1,len(folder)):
if ((folder[i])[:prev_folder_n] == prev_folder_slash):
pass
... |
f081fc76f7ff630bbedc802b058af20fbc628ada | jarek-prz/pythonalx | /kolekcje/slowniki.py | 2,192 | 3.5 | 4 | #list []
#tuple()
#dict{}
# dict
print(dict())
pol_ang = {
#"klucz":"wartosc"
"klucz":"key",
"pies": "dog",
"pies": "dog"
}
print(pol_ang)
print(pol_ang["pies"])
if "dog" in pol_ang:
print(pol_ang["pies"])
print(pol_ang.get("dog")) # jeżeli klucza w slowniku n ie ma to dostajemy wartosc None
p... |
a9c2da95b60a92e08a8047f7639d0e0c5759e406 | sumittal/coding-practice | /python/find_equilibrium.py | 1,556 | 3.734375 | 4 | """
Equilibrium index of an array
Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in an arrya A:
A[0] = -7, A[1] = 1, A[2] = 5, A[3] = 2, A[4] = -4, A[5] = 3, A[6]=0
3 is an equilibrium index, because:
A[0] + A[1]... |
f46110aed02847ed8c78a91b8ddb4da6314bf61b | ibsom/Snake | /Diagne.py | 12,784 | 3.609375 | 4 | from tkinter import *
from random import randrange, randint
from time import sleep
class Grille(Canvas):
"""
Spécialisation et configuration d'un Canvas tkinter pour la gestion d'une grille
comportant nb_lig lignes et nb_colonnes, des marges haut, droite, bas, gauche potentiellement différentes
une ta... |
d246546b8f17a35cd2774942ce2b5305dbea610c | domtriola/software-notes | /languages/python/basic-exercises/exercises.py | 229 | 4.0625 | 4 | # Extending list (not idiomatic Python)
class MyList(list):
def each(self, func):
for i in self:
func(i)
a = MyList([1, 2, 3, 4])
b = MyList()
a.each(lambda x: b.append(x * 2))
print(b) # => [2, 4, 6, 8]
|
e5831b5f3b1e25a1954d26c328a71f9565706c53 | wjdghrl11/python_nadoBasic | /24.py | 403 | 3.640625 | 4 | # 출석번호가 1 2 3 4 앞에 100을 붙이기로함 101 102 103 104[한줄 for문]
students = [1,2,3,4,5]
print(students)
students = [i+100 for i in students]
print(students)
# 학생 이름을 길이로 변환
students = ["iron", "thor", "groot"]
students = [len(i) for i in students]
print(students)
# 학생 이름을 대문자로 변환
students = [i.upper() for i in students]
print(... |
a0dbfe780161be15f403f2a0fb01eb957ab2ffa7 | GunnerX/leetcode | /链表汇总/面试题18. 删除链表的节点.py | 1,154 | 4 | 4 | # 给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
#
# 返回删除后的链表的头节点。
#
# 注意:此题对比原题有改动
#
# 示例 1:
#
# 输入: head = [4,5,1,9], val = 5
# 输出: [4,1,9]
# 解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
#... |
390398be7d97efd4b50914bd79757c160c81314d | comorina/Ducat_class_code | /p31.py | 80 | 3.875 | 4 | a=float(input("enter 1st num:"))
b=float(input("enter 2nd num:"))
print(a+b)
|
b1f626048f03f39f0b05398e0ebd0ecc679c5b01 | 2100030721/Hackerrank-Artificial-Intelligence | /Probability-Statistics-Foundations/basic-probability-puzzles-3.py | 1,101 | 3.609375 | 4 | # Objective
# In this challenge, we practice calculating probability.
# Task
# There are 3 urns: X, Y and Z.
# Urn X contains 4 red balls and 3 black balls.
# Urn Y contains 5 red balls and 4 black balls.
# Urn Z contains 4 red balls and 4 black balls.
# One ball is drawn from each urn. What is the probability
# tha... |
a3a4c1dd15a13f440c1748bd28724a25a4c9d01e | shanidata78/Learning | /test.py | 152 | 3.625 | 4 | a = [11,22,33]
print 22 in a
b = []
b.append('aaa')
b.append('bbb')
b.append('ccc')
b.append('ddd')
b.append('eee')
print b
for item in b:
print item |
5c10c65b6cc2182bc8b11396a908f6ce8af04195 | Vlas7528/Tensor-Homework | /lesson-5/6 - калькулятор базовых операций.py | 3,386 | 4.1875 | 4 | from decimal import Decimal
result = []
def plus(n1, n2):
n3 = n1 + n2
result.append(n3)
return n3
def minus(n1, n2):
n3 = n1 - n2
result.append(n3)
return n3
def division(n1, n2):
try:
n3 = n1 / n2
except Exception as e:
# print(e)
print('На ноль ... |
1e19d66fdc4e30bb9f2cc44a4aca750664a412a6 | idan57/PTML-Final_Proj | /data_containers/task.py | 1,269 | 3.703125 | 4 | import logging
from threading import Thread
class TaskResult(object):
"""
A class for a task's result
"""
def __init__(self):
self.verdict = False
self.result_value = None
class Task(object):
"""
A class to represent a task
"""
_thread: Thread
result: TaskResult
... |
505192152469949f116759400c72183b299c8625 | gbarboteau/Advent-of-Code-2020 | /Day10/main.py | 1,003 | 3.828125 | 4 | #You can find the puzzle here: https://adventofcode.com/2020/day/10
import sys
#The file containing every numbers
filename = sys.argv[-1]
# =====================
# PART 1
# =====================
#Count the number of different jolt differences
def count_jolt_differences(adaptaters_list):
jolt_dif_list = [... |
9c689e516aca0a26b910c8894dbc7c58bdb40523 | YorkFish/git_study | /ProgrammerAlgorithmInterview/Chapter01/01_11_determine_if_two_linked_lists_cross_02.py | 3,272 | 4.15625 | 4 | #!/usr/bin/env python3
#coding:utf-8
# import 01_06_check_if_linked_list_has_ring_03 as ring # 模块名带了下划线,不好使
class LNode(object):
def __init__(self, x=None):
self.val = x
self.next = None
# 将 head1 的尾部链到 head2 的头部,形成一个有环单链表,然后可套用 01_06 的解法
def concatenate(head1, head2):
cur = head1.next
whil... |
6fde976d391c6f82a9f0b3601790755ef2cb3e5e | devmukul44/Play_Crawler | /model/thread_check.py | 330 | 3.640625 | 4 | import thread
import time
# Define a function for the thread
def print_time(threadName):
print threadName
# Create two threads as follows
try:
thread.start_new_thread( print_time, ("Thread-1",) )
thread.start_new_thread( print_time, ("Thread-2",) )
except:
print "Error: unable to start thread"
while 1... |
3d89bf736446d6b3a1d6b06a616a03e39594c9c7 | Manoji97/Data-Structures-Algorithms-Complete | /Python/1_ProblemsolvingPatterns/1_frequencyCounter.py | 310 | 3.53125 | 4 |
def FrequencyCounter(lst1, lst2):
if len(lst1) != len(lst2): return False
lst1_dict = {}
for i in lst1:
if i in lst1_dict: lst1_dict[i] += 1
else: lst1_dict[i] = 1
for i in lst2:
if i not in lst1_dict: return False
if lst1_dict[i] == 0: return False
else: lst1_dict[i] -= 1
return True
|
0d2fa24c4814bb3b578a6c51209e15f4efbd435f | leehm00/pyexamples | /NUS_pyexercise/35.py | 359 | 3.78125 | 4 | # _*_ coding.utf-8 _*_
# 开发人员 : leehm
# 开发时间 : 2020/7/1 18:42
# 文件名称 : 35.py
# 开发工具 : PyCharm
a = input()
s = a.split()
count = 1
for i in range(1, int(s[0])+1):
if not (i % 3 == 0 or i % 5 == 0 or str(i).count('5') > 0 or str(i).count('3') > 0):
print(i)
count += 1
if count > int(s[1]):
... |
28595bc1247f7cdb9e2d594da389bfab99fee199 | sculzx007/Python-practice | /小甲鱼/第九课 求100-999内水仙花数【没有理解】.py | 1,056 | 3.78125 | 4 | #coding=utf-8
# 原题
"""
编写一个程序,求 100~999 之间的所有水仙花数。
如果一个 3 位数等于其各位数字的立方和,则称这个数为水仙花数。
例如:153 = 1^3 + 5^3 + 3^3,因此 153 就是一个水仙花数。
"""
# 个人答案
"""
j = ... |
fd63d47de1cf5682a3b53b215ae89bb10426ed29 | turksoyomer/TicTacToe-AI | /codes/tictactoe.py | 2,849 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
@author: turksoyomer
"""
class TicTacToe:
def __init__(self):
self.turn = 1
self.player1_marker = "X"
self.player2_marker = "O"
self.state = ["_", "_", "_", "_", "_", "_", "_", "_", "_"]
self.winner = None
self.action_list = list(range(9))... |
8b706bfa2b809d02decf76cbf5c697cd2a8948ad | ridersw/Karumanchi--Data-Structures | /stackDeque.py | 2,633 | 4.09375 | 4 | #operations-
#append(x) - Add x to the right side of the deque.
#appendleft(x) - Add x to the left side of the deque.
#clear()- Remove all elements from the deque leaving it with length 0.
#copy() - Create a shallow copy of the deque.
#count(x) - Count the number of deque elements equal to x.
#extend(... |
98acf53b0f0e8bf1cc399a86149952b4a7ec09c1 | boboalex/LeetcodeExercise | /offer_15.py | 397 | 3.828125 | 4 | class Singleton(object):
def __new__(cls):
# 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton, cls).__new__(cls)
return cls.instance
obj1 = Singleton()
obj2 = Singleton()
obj1.attr1 = 'value1'
print(obj1.attr1, obj2.attr1)
p... |
c88ca837eb9b3703b37449a62ec9ff9a9524299e | aliceayres/leetcode-practice | /practice/leetcode/algorithm/796_RotateString.py | 1,129 | 3.859375 | 4 | """
796. Rotate String
We are given two strings, A and B.
A shift on A consists of taking string A and moving the leftmost character to the rightmost position.
For example, if A = 'abcde', then it will be 'bcdea' after one shift on A.
Return True if and only if A can become B after some number of shifts on A.
Example 1... |
3a30952ecdc154ae46b242edabe8839641fbd008 | mukund7296/Python-Brushup | /19 Switch function.py | 380 | 3.796875 | 4 | #switch python
def get_car_color(car):
if car == 'ford':
return ['red', 'black', 'white', 'silver', 'gold']
elif car == 'audi':
return ['black', 'white']
elif car == 'volkswagen':
return ['purple', 'orange', 'green']
elif car == 'mercedes':
return ['black']
... |
00990e80e83ac1c0e4ffdee31c736a351b6f90ef | PanMartinez/Codewars_Training | /Python Kyu6/Counting Duplicates.py | 314 | 3.640625 | 4 | from collections import Counter
def duplicate_count(text):
dubles = 0
for key,value in Counter(list(text.upper())).items():
if value > 1:
dubles += 1
return dubles
print(duplicate_count("abcde"), 0)
print(duplicate_count("abcdea"), 1)
print(duplicate_count("indivisibility"), 1)
|
1e2be84106093f3fad4f95e7d38b380931b6ac45 | Jjschwartz/RL-an-intro | /experiments/util.py | 2,667 | 3.859375 | 4 | import numpy as np
import matplotlib.pyplot as plt
import time
def run_experiment(agent, timesteps, num_episodes, verbose=True):
"""
Run an experiment using agent, for given number of episodes.
Arguments:
----------
Agent agent : the agent to run experiment with
int timesteps : number of time... |
968959850a0d0abd1b60289c0ecc279b18dba4db | nbenlin/beginners-python-examples | /1-Basic Python Objects and Data Structures/2_exapmle.py | 222 | 4.28125 | 4 | # Take the two perpendicular sides (a, b) of a right triangle from the user and try to find the length of the hypotenuse.
a = int(input("a: "))
b = int(input("b: "))
c = (a ** 2 + b ** 2) ** 0.5
print("Hypotenuse: ", c)
|
db931420fcacf15b146461b27cf1bc85039afd5f | MorrillD/Settlers-of-Catan | /setUpFuncs.py | 14,484 | 3.9375 | 4 | from main import *
import pygame
import sys
# player places first two settlements
# never used after the game is set up
def setUpSettlement(turn, board, screen):
myfont = pygame.font.SysFont("monospace", 20, True)
if turn:
text = "Player 1 place a settlement"
else:
text = "Pl... |
c6c04a62147cbe69cb237ac43fb41867bf72b39e | Prev/leetcode | /problems/44-wildcard-matching/solution-nm.py | 2,065 | 3.671875 | 4 | """
Problem: https://leetcode.com/problems/wildcard-matching/
Author: Youngsoo Lee
Time complexity: O(nm) where n is length of `s` and
m is length of `p`.
"""
from typing import List
class Solution:
def _search(self, s: str, p: str) -> bool:
""" Search string with pattern without wildcard... |
ed884d04afde74b7d090a5871b57124f26afb406 | zerghua/leetcode-python | /N2217_FindPalindromeWithFixedLength.py | 2,993 | 3.890625 | 4 | #
# Create by Hua on 7/19/22
#
"""
Given an integer array queries and a positive integer intLength, return an array answer where answer[i] is either the queries[i]th smallest positive palindrome of length intLength or -1 if no such palindrome exists.
A palindrome is a number that reads the same backwards and forwards... |
fff5269fcd61758b1b52a966aa1667857f6a9031 | frkMaky/cursopython | /gui/practicaCalculadora.py | 4,368 | 3.71875 | 4 | from tkinter import * # Libreria de ventanas
raiz=Tk() # Se crea ventana
miFrame = Frame(raiz) # Se pone frame en la ventana
miFrame.pack() # Se empaqueta todo en la ventana
operacion="" # Operacion a realizar variable GLOBAL
resultado = 0 # Resultado de la operacion
# Pantalla ----------------------------------... |
6ddbc235115f00e34dbaf786e0d043a3593a7254 | YoChen3086/PythonPractice | /exercise14.py | 992 | 3.609375 | 4 | # 题目:
# 将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
def reduceNum(n):
checkNumber(n)
breakDown(n)
# elif n in [1] :
# print ('{}'.format(n))
# while n not in [1] : # 循环保证递归
# for index in range(2, n + 1) :
# if n % index == 0:
# n /= index # n 等于 n/index
# ... |
37bb9a5016af056ca5fa64040311b1b15042cf29 | ahwang16/W4111-f18 | /Projects/HW1-Templates/Python/CSVTableV2-Template.py | 1,896 | 4.125 | 4 | import csv # Python package for reading and writing CSV files.
import copy # Copy data structures.
# hello
import sys,os
# You can change to wherever you want to place your CSV files.
rel_path = os.path.realpath('./Data')
class CSVTable():
# Change to wherever you want to save the CSV files.
... |
a6c94ee20bbd3fc35558cb022a35fb54c520cee4 | TharindaNimnajith/machine-learning | /python_data_science/numpy_package.py | 2,162 | 4.34375 | 4 | import numpy as np
# In Python, lists are used to store data.
# NumPy provides an array structure for performing operations with data.
# NumPy arrays are faster and more compact than lists.
# NumPy arrays are homogeneous.
# They can contain only a single data type, while lists can contain multiple different types of ... |
3881317e280565430fb14c89c650f30adf131165 | pramodswainn/LeetCode | /Week6/92.py | 732 | 3.765625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
current=head
array=[]
while current:
... |
12006e693f527c96b21fa161c1e51d9526932970 | lohitakshapatra/C103 | /line.py | 186 | 3.578125 | 4 | import plotly.express as px
import pandas as pd
df=pd.read_csv("line_chart.csv")
fig=px.line(df,x="Year",y="Per capita income",color="Country",title="Per capita income")
fig.show() |
a4dfa2494ef4111d64fd0ae3bb65392ac3d427d3 | harshavardhanb77/ns | /8a.py | 388 | 4 | 4 | def highest(names,marks):
if(len(marks)==len(names)):
maxMark=max(marks)
index=marks.index(maxMark)
maxName=names[index]
return(maxName,maxMark)
names=[]
marks=[]
n=int(input("Enter the number of students"))
for i in range(n):
names.append(input("name"))
... |
979acf878605e41b9385caca9a807329ca6f66fd | shahpriyesh/PracticeCode | /HashMapQuestions/UncommonWordsFromTwoSentences.py | 703 | 3.6875 | 4 | from collections import Counter
class Solution:
def findUncommon(self, A, B):
cntr_a = Counter(A.split())
cntr_b = Counter(B.split())
res = []
res.extend(self._retrieveUncommon(cntr_a, cntr_b))
res.extend(self._retrieveUncommon(cntr_b, cntr_a))
return res
def _... |
4c9821c6f9fd7e6da655f18b524ce1aa22569f69 | tmdenddl/Python | /Abstraction/Change Calculator.py | 744 | 3.828125 | 4 | from builtins import int
def calculate_change(payment, cost):
change = payment - cost
fifty_thousand_count = int(change / 50000)
change = change % 50000
ten_thousand_count = int(change / 10000)
change = change % 10000
five_thousand_count = int(change / 5000)
change = change % 5000
... |
20a4b5161faf42000927b1bd7edf1c2c782337b3 | PratikPatni/pythoncodes | /rainbow.py | 233 | 3.578125 | 4 | n=int(input())
output=list()
for i in range(n):
s=int(input())
ls=list()
ls=input().split(' ')
ls2=ls
ls.reverse()
if(ls2==ls):output.append("yes")
else:output.append("no")
for i in range(output):print(i)
|
4c23c97551f52a8ca5ff72c120377ce3a6d7b86a | wilsonify/ThinkBayes2 | /tests/test_examples/test_pair_dice.py | 5,915 | 3.703125 | 4 | """
The pair of dice problem
Copyright 2018 Allen Downey
MIT License: https://opensource.org/licenses/MIT
"""
import logging
import numpy as np
import pandas as pd
from thinkbayes import Pmf, Suite
from thinkbayes import thinkplot
def test_BayesTable():
# ### The BayesTable class
#
# Here's the class tha... |
cf674c33fbe152f4a42b3c72c79e05e8b1934e6b | 500poundbear/mlrecipe | /FoodIngredientRecorder.py | 1,507 | 3.6875 | 4 | """
Stores food and ingredient for easy lookup
"""
class FoodIngredientRecorder:
def __init__(self):
# food comes originally with an id
# our internal id is represented by int
self.food_int_to_id = {}
self.food_id_to_int = {}
self.fcount = 0
self.icount = 0
... |
21de5a886dbc3b90c8a0ebe95198e94274f812cb | VineeS/Python | /Assignment1/Prime_numbers.py | 348 | 3.921875 | 4 | import math
max_num = int(input("Max Number"))
primes = [2]
test_num = 3
while test_num < max_num:
i = 0
while primes[i] < math.sqrt(test_num):
if (test_num % primes[i]) == 0:
test_num += 1
break
else:
i += 1
else:
primes.append(test_num)
... |
c4f329dd534d58dcbb6717d0fe7c31d9bf257b2d | tyokinuhata/nlp100 | /06.py | 533 | 3.71875 | 4 | # 06. 集合
# "paraparaparadise"と"paragraph"に含まれる文字bi-gramの集合を,それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.さらに,'se'というbi-gramがXおよびYに含まれるかどうかを調べよ.
n_gram = lambda str: {str[i:i + 2] for i in range(len(str) - 1)}
x = n_gram('paraparaparadise')
y = n_gram('paragraph')
# 和集合, 積集合, 差集合, xに"se"が含まれるか, yに"se"が含まれるか
print(x | y, x & y,... |
8a0ba1fb7988f8911b5ff68363f855d458cbfccd | cjdeguzman95/Python-Glossary | /Other/Simple code examples.py | 4,726 | 4.28125 | 4 | from random import randrange
import pyodbc
# Palindrome function uses slicing and control flow statements to find define palindromes in a given list
def palindrome():
words = ["mum", "bee", "holiday", "hannah"]
for word in words:
reversed_word = word[::-1]
if word == reversed_word:
... |
163f434c9a6af12ad83e515c1d509d0612c0689a | Adrian96119/Miniproyect | /miniproyect_juego_ahorcado/descripcion.py | 1,504 | 4.03125 | 4 | def descripcion():
dibujo_ahorcado = open("ficheros_dibujo/9.txt")#importo el dibujo del ahorcado entero desde ficheros_dibujo para el titulo
print("\n\n") #Hago dos saltos de linea para que no me quede tan arriba el texto
print(dibujo_ahorcado.read()," -------------------********¡JUEGO DEL AHORCADO!****... |
a73fb839c927bdc5438f28740b575df17fb68789 | cossentino/2_linked_lists | /2.6_is_palindrome.py | 848 | 3.65625 | 4 | from linked_list_obj import Node, LinkedList
n1 = Node(5)
n2 = Node(6)
n3 = Node(7)
n4 = Node(6)
n5 = Node(5)
n1.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
def reverse_and_clone(head_node):
curr_0 = head_node
curr = Node(curr_0.val)
prev = None
nextt = None
while curr_0.next:
nextt = Node(curr_0... |
cb8ad6ef50e1dab7e61c6251c8d93e470469392d | ariannedee/intro-to-python | /Problems/Solutions/problem_9_card_hands.py | 385 | 3.859375 | 4 | """
Deal a hand of 5 cards
"""
import random
suits = ['♠︎', '♣︎', '♥︎', '♦︎']
values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
cards = []
hand = []
for suit in suits:
for value in values:
cards.append(suit + value)
for num in range(5):
card = random.choice(cards)
hand.... |
93221a241477debcb2bb3c2d793be091be5a6df3 | mahdibz97/holbertonschool-higher_level_programming | /0x0B-python-input_output/7-save_to_json_file.py | 283 | 3.921875 | 4 | #!/usr/bin/python3
"""Define class"""
import json
def save_to_json_file(my_obj, filename):
"""writes an Object to a text file, using a JSON representation"""
with open(filename, mode='w', encoding='UTF8') as f:
my_str = json.dumps(my_obj)
f.write(my_str)
|
c38f02eb2c2f6fe116f4d13773e622365428866b | siddarthjha/Deep-Learning | /CNN/cnn.py | 7,947 | 3.9375 | 4 | """
This is a 5 layers Sequential Convolutional Neural Network for digits recognition trained on MNIST dataset.
Firstly, I will prepare the data (handwritten digits images) then i will focus on the CNN modeling and evaluation.
It follows three main parts:
The data preparation
The CNN modeling and evaluation
The resu... |
bb15b4f27a1286c8f2f3d8d4136a9c7df7bd494d | its-rose/Python_3.8_Classwork | /OOP3.py | 2,690 | 3.765625 | 4 | # Магичеcкие методы
# Method __hash__
# class User:
# def __init__(self, name, email):
# self.name = name
# self.email = email
#
# def __hash__(self):
# return hash(self.email)
#
# def __eq__(self, obj):
# return self.email == obj.email
#
# john = User('John Connor', 'john@g... |
cb5276198a5c3483b0d2b0f414fba9ec6850d886 | wysocki-lukasz/CODEME-homework | /04_Kolekcje/1_Zadanie_1.py | 287 | 3.640625 | 4 | # Stwórz listę przedmiotów, które zabierzesz na samotną wyprawę w góry.
# Elementy na liście posortuj alfabetycznie, a następnie wyświetl.
items = ['ksiazka', 'termos', 'czpka', 'mapa', 'plecka', 'aparat']
print(items)
items_mod = sorted(items, key=str.lower)
print(items_mod) |
5a22eed6b3901f81239e26d93e18ef0a610043af | santhosh-kumar/AlgorithmsAndDataStructures | /python/problems/array/find_min_in_sorted_rotated_array_with_duplicates.py | 1,623 | 3.84375 | 4 | """
Find Min In Sorted Rotated Array (with duplicates)
If the rotated sorted array could contain duplicates? Is your algorithm still O(log n) in
runtime complexity?
"""
from common.problem import Problem
class FindMinInSortedRotatedArrayWithDuplicates(Problem):
"""
Find Min In Sorted Rotated Array (with dupl... |
caa991d0433433cc864ce92644f346721c978c29 | digitalMirko/PythonReview | /python_review10_file_io.py | 1,047 | 3.875 | 4 | # Python Programming Review
# file name: python_review10_file_io.py
# JetBrains PyCharm 4.5.4 under Python 3.5.0
import random # random number generator
import sys # sys module
import os # operating system
# file io or input output
# create or open a file
# opening a file called "test.txt", wb allows you to... |
6f6706447e564cbd6f16fff3fe2b905d2d7e3fdb | ugiacoman/Basics | /02calc/cylinder.py | 784 | 4.6875 | 5 | # CS 141 lab 2
# cylinder.py
#
# Modified by: Ulises Giacoman
#
# This program calculates the volume, surface area and circumference of
# a cylinder with values for the radius and height provided by the user
import math
# Prompts and converts to float the radius and height of the cylinder
radius = float(input("Enter ... |
2303ea5af1614c9f10efa4e3ecc22b61b2a30d84 | SimplyClueless/DigitalSolutions2021 | /Classwork/Python/ConsecutiveLetters.py | 205 | 3.8125 | 4 | def consecutiveLetters(word):
for cycle in range(0, len(word), 1):
if word[cycle-1:cycle] == word[cycle:cycle+1]: return True
return False
print(consecutiveLetters(input("Enter a word: "))) |
3a08c46d3f642e171a1fcda873dca9e20004cfdd | AadityaDeshpande/LP3 | /assign7/diffie.py | 899 | 3.828125 | 4 | import random
def generateKey():
num1=random.randint(2,9999)
num2=random.randint(2,9999)
flag=isPrime(num1)
flag2=isPrime(num2)
if flag==0 and flag2==0:
print("{} and {} is a prime number".format(num1,num2))
x=random.randint(0,9999)
print("x is {}".format(x))
y=rando... |
efcdaac5d6670c562bd356f06a68d5c860ede1af | akshitMadaan/CustomUserModel | /function.py | 393 | 3.859375 | 4 | x = int(input("Enter the value of x:"))
print (x)
print(type(x))
n = int(input("Enter the value of n:"))
print(n)
print(type(n))
sum=0
def first(x,n):
sum=0
for i in range(1,n+1):
sum += 1/x**i
print(sum)
first(x,n)
def second(x,n,sum):
if n==0:
return 0
else:
sum = 1/(x**n)... |
e1f5e702940c2473b3cf2a7e287d89e95a7bcac8 | Superbeet/PrimeMultiplicationTable | /PrimeMultiplicationTable.py | 3,779 | 3.859375 | 4 | import math
class PrimeMultiplicationTable(object):
def get_primes_3(self, num):
"""
Time Complexity = O(N) Space = O(N)
"""
if num <= 0:
return []
if num == 1:
return [2]
size = self.prime_bound(num)
res = []
count = 0
... |
d6032c898cd6e7aa306a4e701290877c70b1fb11 | matheus-Casagrande/ProjetoSudoku-ES4A4 | /testes/testes_Ranking/teste1_confereExistenciaArquivo.py | 1,368 | 3.5625 | 4 | '''
Este teste serve para testar a existência do arquivo 'ranking.txt' no diretório 'jogo'
Neste módulo, importa-se o módulo "posiciona_amostra" que vai tentar copiar o arquivo
se o mesmo existir na pasta 'jogo'. Se não for criado um 'ranking.txt' dentro dessa
pasta de testes, é porque o ranking.txt original não exist... |
6451affd3d7597ca1f26cf5bf1110362a2865cf8 | shradhakapoor/practice-codes | /binary_search_tree.py | 20,179 | 3.78125 | 4 | import os
__path__ = [os.path.dirname(os.path.abspath(__file__))]
from . import binary_tree
class Queue(object):
def __init__(self):
self.items = []
def enqueue( self, item ):
self.items.insert(0, item)
def dequeue( self ):
return self.items.pop()
def is_empty( self ):
... |
f135f48ec8203046e3adb8beca1517eee02fa451 | wangfeng351/Python-learning | /语法基础/practise/数据库操作.py | 503 | 3.5625 | 4 | """
数据库常规操作
"""
import pymysql
def data_select():
# 数据库连接
db = pymysql.connect("localhost", "root", "root", "db_python")
# 获得游标
cursor = db.cursor()
sql = "SELECT * FROM t_follower WHERE gender>-1"
try:
cursor.execute(sql)
# 执行sql
results = cursor.fetchall()
# ... |
89649a2c7cf069bd45fb91ce69b72a9c5a22ca1d | yuanxu-li/careercup | /chapter8-recursion-and-dynamic-programming/8.5.py | 2,170 | 4.78125 | 5 | # 8.5 Recursive Multiply: Write a recursive function to multiply two numbers without using the * operator.
# You can use additions, subtraction, and bit shifting, but you should minimize the number of those operations.
def multiply_recursive(x, y):
""" x can be seen as x1x2, while y as y1y2.
steps are listed as foll... |
16277b77664f34487b6c135339c76582814413a1 | Adrncalel/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 1,262 | 3.765625 | 4 | #!/usr/bin/python3
"""
This is the matrix_divided module.
It has the function of modifyinf certain
aspects of bidimensional matrixes.
"""
def matrix_divided(matrix, div):
"""This function recieves a bidimensional matrix
and a divisior, it returns the matrix with the values
divided by the given divisor.
... |
4f1274f507b0887e72a77393b8f0663707ea4719 | rheena/Python-basics | /Exception handling.py | 1,106 | 4.34375 | 4 | #When an exception happens the rest of the code does not get executed
#Try and accept statements
try: #put in all the code you want executed if an exception happens, you get into the except block
x = int(input('First number: '))
y = int(input('Second number: '))
print(x / y)
except:
print('Ther... |
93e1dbc2b3d3f8b8e5b2340505b6122800212e7a | xiaotaohe/Python_code | /Python_code/Sequence.py | 3,466 | 4.46875 | 4 | # coding=utf8
#目标:Sequence类型族
#序列类型族(String(字符串)、Tuple(元组)、List(列表))
#字符串操作
a = "Hello, I like python Web Practice"
b = a[1]
print("b = ",b)
b = a[7:13] # I like
print("b = ",b)
print(a[:13]) #Hello, I like
print(a[14:]) #pyth.....
print("like" in a) # True
print(a+"!!") # Hell........ !!
print(a)
print('ABC'*3) #重复... |
3ebd38be546db2e8589a1ff8d8703ede235fb2a1 | asiasarycheva/asia_homework | /HW-3/HW3-1.py | 1,651 | 3.59375 | 4 | import os, re, pickle
patternint = '[0-9]+'
patternengint = '[a-z, A-Z, 0-9]+'
glacierlst = []
countrylst = []
arealst = []
answer = 1
while answer == 1:
glacier = str(input('введите название ледника на русском '))
while re.match(patternengint, glacier):
print('по-русски и без цифр! ')
... |
bbe31b4c967113abc5c2fd562a865c166ef185ca | shaokangtan/python_sandbox | /cruise_interview.py | 657 | 3.875 | 4 | #question: find the time when h, m, s all align on the same tick
seconds = 24 * 60 * 60
def hand_sec(sec):
tick = sec % 60
return tick
def hand_min(sec):
min = sec // 60
tick = min % 60
return tick
def hand_hour(sec):
min = sec // 60
hr = min // 60
tick = hr % 12
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.