blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a92ae8706da2591795b5ad82b587dd164bf25df9 | jun-mok-Oh/python-exercise | /제어문 문제6(수필).py | 320 | 3.546875 | 4 | sentence = "다들 파이썬은 어떠신가요 파이썬은 나중에 다른 곳에서도 많이 쓰인답니다 파이썬은 다른 언어보다 코딩 하기 쉬워요 멋사 멋사 화이팅"
splitsentence = sentence.split()
print(splitsentence)
print(splitsentence.count("파이썬은"))
a= str(sentence)
print(a) |
0e27aa5b827cdef7727c0a50bfacfeaf3813dc22 | stanley98yu/ssp-2016 | /astrophysics/random.py | 1,737 | 3.859375 | 4 | from visual import *
from visual.graph import *
from random import randint
#creates a random 2D walk
def random2D():
#creates ball and trail
ball = sphere(pos=(0,0,0),radius=0.1)
ball.trail = curve(color=color.white)
dt = .01
while 1:
#runs through random walks by randomizing an angle and ... |
ad7467a882e4cea2aefd037073cecc15e88c0195 | ItamarRocha/DailyByte | /week_11/day77_artgallerythief.py | 1,413 | 3.796875 | 4 | """
You’ve broken into an art gallery and want to maximize the value of the paintings you steal.
All the paintings you steal you place in your bag which can hold at most W pounds. Given that
the weight and value of the ith painting is given by weights[i] and values[i] respectively,
return the maximum value you can... |
a72b772dd96c8c7f9949259d0e3284868841b105 | sukritmohan/tictactoe | /rl/QPolicy.py | 2,569 | 3.515625 | 4 | import copy
import random
import pickle
import abc
class QPolicy(object):
def __init__(self, policytype, model, exploration=15, statefile = None):
self.__policytype = policytype
self.setStatefile(statefile)
self.q = model.get('model', {})
self.episode_rewards = model.get('rewards', [])
self.setExploration... |
41fc831772982111bf965b747a64b0870e14b323 | William-Hill/UVI_Teaching_2018 | /turtle_lessons/turtle_racer.py | 1,832 | 4.34375 | 4 | import random
import turtle
import time
STAMP_SIZE = 20
SQUARE_SIZE = 20
FINISH_LINE = 200
COLOR_LIST = ['maroon', 'blue', 'green', 'brown', 'yellow', 'purple']
STARTING_LINE_X = -350
STARTING_LINE_Y = 280
TURTLE_DISTANCE = 90
def draw_starting_line():
'''Creates the starting line where the turtles start to race ... |
0254410554606fc65716888e127ae0fbfa655b3a | aluramh/DailyCodingProblems | /DailyCodingProblems/problem94.py | 3,731 | 3.953125 | 4 | class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def traverse(tree_root):
"""
Traverse the tree and print the values of each node.
Adaptation of a DFS search.
"""
start = None
end = None
def helper(r... |
ac7176504b52fcde2368744b47e6778472ad9a6e | robinn00/StudyDemos | /Python/mytest/test2.py | 838 | 3.828125 | 4 | #! /usr/bin/python
# _*_ coding:utf-8 _*_
# 文件名:test2.py
import sys,os
import random
print "Content-type:text/html"
print
var1,var2,var3 = "r1","r2","r3"
num1 = 10
num2 = 40
print(var1+"\n"+var2+"\n"+var3+'\n')
print(num2)
del num2
print(num1)
num = random.choice(range(10))
print("\n<br>\n")
print(num)
ranNUM = ra... |
ed9e4ee218c3d4e1c56e7507aef02e266d0dfe18 | Loskiz/AS_CS_Homework | /May 20 Monday 2019/ProblemSet1_1.py | 163 | 3.90625 | 4 | s="asjdfhdsaflalsdjfhl"
vowels=['a','e','i','o','u']
counter = 0
for letter in s:
if letter in vowels:
counter+=1
print("Number of vowels: ",counter)
|
ee6bb1297d2b088816eaf2b9a89a5946e3689b20 | SilasA/Random-Scripts | /rent-calc.py | 985 | 3.71875 | 4 | #!/usr/bin/python3
# Store rent in cents
print("Enter total rent: $", end="")
rent = int(float(input()) * 100)
print("Enter total sqft: ", end="")
total_area = int(input())
print("Enter the number of residents: ", end="")
num_beds = int(input())
beds = []
bed_area = 0
for i in range(num_beds):
print("Enter nam... |
0a3a2f791cb7ed0dda892259af8210565e6807b0 | autsav/pthon_basic | /class.py | 1,499 | 4.34375 | 4 | class Person():
def insert(self,name,age,idNum):
self.name=name
self.age = age
self.idNum = idNum
def output(self):
print("your name is " + self.name +" Your age is "+self.age+" your ID is " +self.idNum)
# insert(self="yes",name="utsab",age=14,idNum=23)
#After Creating... |
6170e63ac2ccec766c550e8adbb628f2fd366dcd | markd87/markd87.github.io | /assets/fractals/chaos.py | 1,065 | 3.609375 | 4 | class Chaos:
"""
Models the dynamical system with :math:`x_{t+1} = r x_t (1 - x_t)`
"""
def __init__(self, x0, r):
"""
Initialize with state x0 and parameter r
"""
self.x, self.r = x0, r
def update(self):
"Apply the map to update state."
self... |
3622437d14e4aa0fc20324be5ee151c6c3680906 | daglyd/StudieArbeid | /IN1900/Week 2/ball_table2.py | 742 | 3.6875 | 4 | #Exercise 2.9: Store values from a formula in list
#Variables used
v0 = 2.0
g = 9.81
tend = 2*v0/g #Last t value
n = 5 #Number of uniformly spaced t values
#Lists for t and y values
T = []
Y = []
#Creating and adding t,y values to the two lists
for x in range(0,n+1):
t = (tend/n)*x
y = v0*t - 0.... |
a970b179bc1e5e54dacfecd77895cf204634d858 | victorss01/kitabisa_DE_Test | /prime_number.py | 483 | 3.78125 | 4 | def prime(n):
#nilai awal
ls = [2,3]
#pengandaian jika n < 3 maka return nilai awal
if (n < 3):
return ls[:n]
#pengandaian hingga beroleh bilangan prima
for i in range(2,n):
generate = ls[-1]+2
while any(not(generate%num) for num in ls):
generate += 2
... |
e25156382591fd0483b4516fdb91aacfe4aedee7 | TVChatten/ATMMockProject | /ATMProject.py | 4,409 | 3.78125 | 4 | import datetime
import random
import validation
import database
from getpass import getpass
# database = {} #dictionary
currentDatetime = datetime.datetime.now()
def init():
isValidOptionSelected = False
print("WELCOME TO THE CLOVER ATM")
while isValidOptionSelected == False:
haveAccount = ... |
10648bc4fc8f23f847f120f2b113992a03f5b502 | Jananisethu1810/LabAssignments | /PythonPrograms/excel.py | 3,163 | 3.734375 | 4 | import pandas
'''
This function is used for finding all the assignee names for the given assignment group
'''
def find_assignee_name(assignment_group, summary):
assignee=[]
criteria_both=findersheet.loc[
(findersheet['Assignment Group']==assignment_group) &
(findersheet['Selection Criteria']=='... |
bb55850f4f67199c5f332e1d2dc57949f6f5cded | ohmema/interview | /python/interviews/tree/arithmetic_tree.py | 2,085 | 3.703125 | 4 | """
Give an Node
{
Node getLeft();
Node getRight();
String toString();
}
Give a root nodeNode root
*
/ \
+ -
/ \ / \
1 2 3 4
Return(1 + 2) * (3 - 4)
If (1 + 2) + (3 + 4)
doesnot need to be bracketed Only leaf nodes are numbers
followup Give you * + 1 2 - 3 4 to return this tr... |
043db09c8364f906dce350970f4a6e3f35972b73 | Victor-opus/Python-together | /5月15日Chapter21Print/numTest.py | 82 | 3.625 | 4 | num=8.0
for i in range(1,int(num)+1):
print "%d/%d = %.3f"%(i,num,i/num)
|
7508af076e6f85b5235521e75b5e406c0d54e3c0 | kdolic/cs-guided-project-python-ii | /src/demonstration_04.py | 1,202 | 4.375 | 4 | """
Challenge #4:
Create a function that changes specific words into emoticons. Given a sentence
as a string, replace the words `smile`, `grin`, `sad`, and `mad` with their
corresponding emoticons.
word -> emoticon
---
smile -> :D
grin -> :)
sad -> :(
mad -> :P
Examples:
- emotify("Make me smile") ➞ "Make me :D"
- emot... |
6eb6dedb699cfc8363c39144d58d1b687bb3d5e3 | bentondavidl/ProjectEuler | /Python/(38)Pandigital multiples.py | 639 | 3.53125 | 4 | from itertools import permutations
pan = permutations('123456789')
pan = [int(''.join(x)) for x in pan]
def check_pandigital(num):
num_int = int(num)
if len(str(num)) != 9:
return False
if any([num_int == x for x in pan]):
return True
return False
def get_concat(num):
total = ... |
72cb24d5beabede4a646dba3a4cdc0cae4ce6689 | zaoyuaner/Learning-materials | /python1901/1_python基础/day03/5.科普.py | 310 | 3.609375 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
# author:zhangjiao
a = "" #0 False None "" [] {} ()
#
if a:
print("真")
else:
print("假")
'''
在判断的过程中,取值为假的:0、False、None、"",[],{},()
'''
print(False and 8)
print(6 and True and 7)
print(8 and 6)
print(0 and False) |
1c503d99f36d78e4eac59258b331318bf97256d1 | hovermeyer/exercism | /python/raindrops/raindrops.py | 192 | 3.609375 | 4 | def convert(number):
#adjusted for a list comprehension.
speak = [s for f, s in [(3, 'Pling'),(5,'Plang'),(7,"Plong")] if number % f ==0]
return "".join(speak) or str(number)
|
1386a011ae3ae486890278b686394215eec359cc | rahsinha2/Artificial_Intelligence | /assign1/rahsinha-hw1.py | 13,442 | 4.125 | 4 | ##################################################
# Submitted by : Rahul Sinha
# User name : rahsinha
##################################################
from random import randint
##################################################
# method : move_gen()
# returns: position in the range 1-9
# move generator fo... |
90b8432a6d2a58aa59aed4dbca558ebc91e8d76a | sunshinewxz/leetcode | /592-fractionAddition.py | 959 | 3.5625 | 4 | import math
import re
# solution 1
class Solution:
def fractionAddition(self, expression):
"""
:type expression: str
:rtype: str
"""
# nums = map(int, re.findall('[+-]?\d+', expression))
nums = re.findall('[+-]?\d+', expression)
# nums = map(int, re.findall('[... |
34983612e48d3de8bebdee24a66f3571cb76e011 | SourabhShenoy/Python-Code | /Google Foobar/GitCodes/foobar-master-8/lineUpTheCaptives.py | 3,075 | 4.28125 | 4 | from itertools import permutations
from math import factorial
"""
You need to calculate the number of ways that rabbits can be lined up such that a
viewer on one end sees x rabbits, and a viewer on the other end sees y rabbits, because
some taller rabbits block the view of the shorter ones.
For example, if rabbits w... |
31cb070021fd652796d0efd8dca7fdd9934a1ad4 | JustAn0therDev/python_face_recognition | /FaceRecognition.py | 1,007 | 3.578125 | 4 | from PIL import Image
import face_recognition
class FaceRecognition:
__image_location = ''
def set_image_location(self, image_location: str) -> None:
self.__image_location = image_location
def get_image_location(self):
return self.__image_location
def show_faces_in_image(self) -> No... |
182e22bf924030e57e37e34c4a08b91080ee7640 | muzikovam/pyladies | /piskvorky/piskvorky.py | 1,360 | 3.71875 | 4 | from random import randint
from ai import tah_pocitace, tah
def vyhodnot(pole):
if 'xxx' in pole:
return 'x'
elif 'ooo' in pole:
return 'o'
elif '-' not in pole: # Nikdy nepouzivejte not '-' in pole, je to mene citelne
return '!'
else:
return '-'
def tah_hrace(pol... |
8fab5c40c74c739c18ce57939c29b07c54385943 | Kanupreet/Assignments | /task2/ques4.py | 170 | 3.84375 | 4 |
while True:
num = eval(input("Please enter a no."))
if num < 0:
print("It's over")
break
else:
print("Good Going")
continue
|
70dcc8de5da0dd9c03d364c318c98fa2e9ba5787 | ZihengZZH/LeetCode | /py/PoorPigs.py | 1,292 | 3.90625 | 4 | '''
There are 1000 buckets, one and only one of them contains poison, the rest are filled with water.
They all look the same.
If a pig drinks that poison it will die within 15 minutes.
What is the minimum amount of pigs you need to figure out which bucket contains the poison within one hour.
Answer this question, ... |
306e9d687841d256627a77f0bd0a32088e6a5654 | janakparmar9491/The-Complete-Python-Masterclass-Learn-Python-From-Scratch | /2-Control-Structure-In-Python/7-For-Loop.py | 132 | 3.890625 | 4 | for x in range(1,6):
print(x)
print("Janak")
fruits = ["Apple", "Banana", "Peach", "Orange"]
for x in fruits:
print(x) |
1c4eee19d184ec74ad60c2914db0af4fca685693 | fengshuai1/1807-2 | /10day/生成器.py | 196 | 3.6875 | 4 | def fib():
a,b = 0,1
# print('haha')
for i in range(10):
# print('111')
#print(b)
yield b
# print('333')
a,b = b,a+b
#print(fib())
G = fib()
#print(next(G))
for i in G:
print(i)
|
9b09ac6b3ac7a4a01f94c7e5986e2f9806125141 | stephenmoye/Python-Programming-Projects | /Chapter 7/rainfall-statistics.py | 812 | 4.375 | 4 | # Rainfall Statistics
# Design a program that lets the user enter the total rainfall for each of 12 months into a list. The
# program should calculate and display the total rainfall for the year, the average monthly rainfall,
# the months with the highest and lowest amounts.
rainData = []
def main():
for month i... |
14f2392b08f917f773d91137c35f90204c9992bf | yulishuta/algorithms-python | /BTSTree.py | 3,285 | 3.84375 | 4 | class BSTree:
def __init__(self,key):
self.key = key
self.left = None
self.right = None
self.height = 0
self.n = 0
self.xAxis = 0
def inOrder(self):
if(self == None): return
inOrder(self.left)
print(self.key, self.xAxis)
inOrder(self.... |
4cd709ae04e80776b797d6ff8935adff2fc858aa | Dhanvinsh99/order-stem-and-leaf-plot | /stem and leaf mathematics.py | 486 | 4.09375 | 4 | print("this is code that helps in organazing data in maths using",
"a system called ordered stem and leaf plot")
n = int(input("no. of tens: "))
a = {'0':[],'1':[],'2':[],'3':[],'4':[],'5':[],'6':[],'7':[],'8':[],'9':[],'10':[],}
for i in range(0, n):
tens = input("tens: ")
x = int(input("no. ... |
f1dca94185c9e63433b1aac564eef0e3d85f0f59 | JSLobo/LTP_Crafting_Quality_Code | /Week2/Assignment/test_swap_k.py | 1,832 | 3.59375 | 4 | import a1
import unittest
class TestSwapK(unittest.TestCase):
""" Test class for function a1.swap_k. """
# Add your test methods for a1.swap_k here.
def test_swap_k_2_items_list_k_zero(self):
"""
Test swap_k where there are 2 items list and
swap the first k items of the list with ... |
ec34671f406367500f224ac56b67fd709ce1907c | epaqu/Leetcode-Interview-Questions-Easy | /strings/valid_palindrome.py | 389 | 3.65625 | 4 | class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.lower()
alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
for c in s:
if c not in alphabet:
s = s.replace(c, "")
if s == s[:... |
66ba8633ee9519e578003c44a27046a65bb91ee4 | JinZiYan2/PythonByJoker | /day03homework.py | 4,178 | 3.890625 | 4 | # 1.五角数
# n = 1
# def getPentagonalNumber(n):
# for n in range(1,101):
# star = n*(3*n-1)/2
# print('%d'%star,end='\t')
# if n % 10 == 0:
# print('')
# getPentagonalNumber(n)
# 2.求一个整数各个数字的和
# def sumDigits(n):
# n = str(input('请输入一个整数:>>'))
# sum = 0
# ... |
b0dbcaa735bf02ef3927ec41d6edb5ae18071f05 | DorivalRamos/exerciosPython | /Aulas/Aula30_06/conta.py | 1,027 | 3.875 | 4 | class Conta:
def __init__(self, titular, saldo=10):
self.titular = titular
self.__saldo = saldo
def __str__(self):
if self.__saldo == 0:
return f'''
Titular: {self.titular}
'''
else:
return f'''
Titula... |
b486e6382888207957af99af712af00f086ab93a | beefoo/coloring-book | /xls2csv.py | 1,674 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# Usage:
# python xls2csv.py -in data/input.xlsx -out output/
# python xls2csv.py -in data/input.xlsx -out output/ -sheet "Sheet 1"
import argparse
import csv
import os
import sys
import xlrd
# input
parser = argparse.ArgumentParser()
parser.add_argument('-in', dest="INPUT_FILE", default=... |
5072eefaae47ecdc9bd8ae1c13613134a4786969 | slamminsammya/Cryptopals | /RSA.py | 1,966 | 3.53125 | 4 | import random
from ModularExponentiation import square_and_multiply as modexp
from RSA_primes import RSA_pair
from RSA_math import extended_gcd, totient, modinv, gcd
class RSA(object):
def __init__(self):
self.primes = self.get_primes()
self.modulus = self.get_modulus()
... |
3709ee183922a54e52ee067cfd40424934683d91 | hernanpesantez/algorithms | /algorithms/approximation/square_root.py | 727 | 4.4375 | 4 | #!/usr/bin/env python
# sqrt.py - find square root
def sqtest(num, orig, ind):
sq = 0
while sq <= orig:
num = num + ind
sq = num * num
num = num - ind
return num
n = float(0) # this is our working number. We start at zero and increment.
innum = int(input("For what number would you lik... |
ab23a8d2fa87d78cb858c72f5d17a90af4972559 | CosminPiscan/Solutions | /TP3/ex3.py | 257 | 3.546875 | 4 | from microbit import display
a = input("La valeur pour a est: ")
b = input("La valeur pour b est: ")
c = input("La valeur pour c est: ")
d = input("La valeur pour d est: ")
result = int(a)+int(b)*int(c)+int(d)
print(result)
#bonus
display.scroll(result) |
324d3e6d1da5a5bb8bc80018b29b23f0e5ff5ec0 | mjxong/CodingTest | /CodeUp/6066 : [기초-조건,선택실행구조] 정수 3개 입력받아 짝,홀 출력하기(설명).py | 185 | 3.671875 | 4 | a, b, c = map(int, input().split())
if a%2 == 0:
print("even")
else:
print("odd")
if b%2 == 0:
print("even")
else:
print("odd")
if c%2 == 0:
print("even")
else:
print("odd") |
4a3feccbf67c7578b1e074480682b5a8b30b30c4 | ChWeiking/PythonTutorial | /Python高级/day37(单链表、算法)/demo/03_普通队列.py | 663 | 4.09375 | 4 | class MyQueue(object):
"""队列"""
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, item):
"""进队列"""
#self.items.append(item)
self.items.insert(0,item)
def dequeue(self):
"""出队列"""
#return self.i... |
28e14be2bbd36a1217e56221c46e92ee9020bd97 | bigchamp/python | /examples/class.py | 910 | 3.796875 | 4 |
class MyClass:
variable = "Blah"
def my_function(self):
print("This is a message inside the class.")
my_own_class = MyClass()
x = my_own_class.variable
print(x)
my_own_class.my_function()
myobjectx = MyClass()
myobjecty = MyClass()
myobjectx.variable = "guzhigak"
myobjecty.variable = "asdasdasd... |
65fdc0a489658c7da80a385321ac39f2695e554f | jiekeman/xuexi | /test1.py | 1,292 | 3.640625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019-9-27 10:44
# @Author : Jie Ke Man
# @FileName: test1.py
# @Software: PyCharm
import re
# def add_sub(string):
# add_regular = ']?\\d*\\.?\\d \\+ [-]?\\d*\\.?\\d '
# sub_regular = '[-]?\\d*\\.?\\d \\- [-]?\\d*\\.?\\d'
# # 一个一个找出加法的格式计算并替换
# while re.findall('a... |
70e246ae0258063b45413731bafd6239385113e4 | Etv500/Python-Basics-to-make-and-break | /funzioni comuni.py | 1,094 | 3.71875 | 4 |
po = [1,2,3,4,5.2]
minpo=min(po)
maxpo=max(po)
maxporounded=round(maxpo)
print(minpo)
print (maxpo)
print (maxporounded)
# Create variables var1 and var2
var1 = [1, 2, 3, 4]
var2 = True
# Print out type of var1
print(type (var1))
# Print out length of var1
print(len(var1))
# Convert va... |
974ea85512982dacd3510218cd36b489ed377293 | Zhengxin-Tang/bryans-algo | /算法和数据结构/algorithm-my-python/nn/insertionSort.py | 708 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/28 21:30
# @Author : Zhengxin Tang 28453093
# @Mail : ztan0030@student.monash.edu
# @File : insertionSort.py
# @Software: PyCharm
from nn.selectionSort import *
def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
current... |
5159c3ab38daa0cb49de5ae4d4b4303e135d26af | Thinkeraty/C-97 | /count_words_function.py | 383 | 4.0625 | 4 | introduction = input("Enter Your Intro: ")
char_count = 0
word_count = 1
def word_count_func(char, words):
for i in introduction:
char = char + 1
if(i == " "):
words = words + 1
print("Number of Words:")
print(words)
print("Number of Characters:... |
477cd7ce391e1db8ab237e475cbeb977e05de86f | harmankaler2000/Python-Practice-Files | /variables.py | 675 | 4.3125 | 4 | name = "harman"
print(name)
#check type
print(type(name))
#concatenate two values
first_name = "Harman"
last_name = "Kaur"
full_name = first_name +" "+ last_name
print("Hello "+ full_name)
age = 21
print(age)
age += 1
print(age)
age -= 1
print(age)
print(type(age))
#error
#error = age + full_name
# TypeError: unsuppor... |
1322e7ffafba423bb0bf14667027363fdd0f9909 | zhaochuanshen/leetcode | /Partition_List.py | 1,448 | 3.953125 | 4 | '''
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
'''
# Definition for s... |
9b494d47f8f947da367ffaa41ae37d0b80ec34d4 | NikhilPrasad0497/Complete-Python-3-Bootcamp | /PythonWorkspace/PythonBootcamp/src/Sctipts/sets.py | 182 | 3.8125 | 4 | ''' sets are unorderec collection of unique objects'''
myset=set()
print(myset)
myset.add(1)
myset.add(2)
myset.add(1)
print(myset)
mylist=[1,1,1,1,2,2,2,2,3,3,3]
print(set(mylist))
|
e154f8124187a343053949cd5b726fee2a5ca2bc | shelyao/LeetCode2020 | /leetcode/editor/en/[1028]Recover a Tree From Preorder Traversal.py | 2,151 | 3.84375 | 4 | # We run a preorder depth-first search (DFS) on the root of a binary tree.
#
# At each node in this traversal, we output D dashes (where D is the depth of t
# his node), then we output the value of this node. If the depth of a node is D, t
# he depth of its immediate child is D + 1. The depth of the root node is 0. ... |
d0eab5c9f05f8c688e3294ea6c8a3ce22ae12c94 | fatjan/code-practices | /python/first-same.py | 252 | 3.859375 | 4 | def firstDuplicate(a):
b = []
for i in range(len(a)):
print(a[i])
if a[i] not in b:
b.append(a[i])
print(b)
else:
return a[i]
return -1
print(firstDuplicate([2, 1, 3, 5, 3, 2]))
|
aca0e80bc040ee3d698d6f60fb590f734ad5e83a | Krieg0-0/LearnPython | /EX19.py | 787 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 17 20:46:05 2019
@author: 薛
"""
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses!")
print(f"You have {boxes_of_crackers} boxes of cracker!")
print("Man that's enough for a party!")
print("Get a b... |
7530542784171450cb96bbbc256f2642bc049cae | Gayathri0024/guvi | /Number guessing.py | 191 | 3.5625 | 4 | import random
def ranfunc():
n=random.randint(0,50)
return n
n=ranfunc()
guess=int(input("Enter ur guess"))
print(n)
if(guess==n):
print("You WIN")
else:
print("You Lost")
|
d04738992f56c71796e333e0084ad4253d8762b3 | wangyu33/LeetCode | /LeetCode257.py | 1,195 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : LeetCode257.py
# Author: WangYu
# Date : 2020-09-04
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
from typing import List
class Solution:
def binaryTre... |
a81cf4e6c71dcf4f59a90f14efb11fef2081f85b | dbconfession78/interview_prep | /leetcode/726-number_of_atoms.py | 4,207 | 4.5 | 4 | # Instructions
"""
Given a chemical formula (given as a string), return the count of each atom.
An atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
1 or more digits representing the count of that element may follow if the count is greater than 1. If... |
0ae535f0c50d9496bc30d16c84210cb3dba54438 | changethisusername/uzh | /Informatik1/MidtermsInfk/midterms hs20/count_keyword.py | 639 | 4.34375 | 4 | # count_keyword_occurrence("This is a short sentence which serves as an example.",["is", "short"])
# should return 3 because "is" occurs twice and "short" occurs once.
def count_keyword_occurrence(string, strings_to_be_searched):
counter = 0
split = []
split.append(string.split(" "))
for word in split... |
7d85128fd214ff15bdd9b417a0a55d2f11b1f477 | shuque/dnsmisc | /ip2binary.py | 849 | 4.03125 | 4 | #!/usr/bin/env python3
"""
Convert a presentation format IP address to its binary representation.
Examples:
$ ip2binary.py 128.91.2.13
10000000010110110000001000001101
$ ip2binary.py 2001:4860:4860::8844
0010000000000001010010000110000001001000011000000000000000000000000000000000000000000000000000000000000000000000... |
9db77e9e2ef4dc0fc85c53e31cc525fe701b538a | csgray/learn-python3 | /ex24.py | 1,679 | 4.34375 | 4 | print("Let's practice everything.")
# This is a single-quote string so we need to escape the apostrophes inside the string
print('You\'d need to know \'bout escapes with \\ that do:')
# Basic formatting with new-lines and tabs
print('\n newlines and \t tabs.')
# Multi-line string with new-lines and tabs
poem ="""
\tTh... |
b41298e9f4c9186ce27b6c77101c9026a4aa9f2d | Soadist/test_task_python | /task_4/client/generators.py | 477 | 3.765625 | 4 | def str_to_array(string):
array = []
try:
for x in string.lstrip('[').rstrip(']').split(','):
if '"' in x or "'" in x or '.' in x or x == ' ':
array.append(x)
elif x == '':
array.append(None)
else:
array.append(int(x))
... |
187210f8d967c423dfc8744333db3c2cf6d6e889 | Grey4114/Python | /Standard/coin_flip/coin_flip.py | 1,865 | 4.03125 | 4 | """
Author: Chris Caprio
Program: Coin Flip Simulation
Details:
Write some code that simulates flipping a single coin however many times the user decides. The code should record
the outcomes and count the number of tails and heads.
"""
# Froms & Imports & Variables
import random
from collections import Counter
# Fu... |
08d303c40b2723d6c015b0467d017a2d8eeac924 | berieo/Algorithms | /Project3/project3.4.py | 1,103 | 3.703125 | 4 | """
多源最短路径算法,采用Floyd算法,对每个点采用Bellman_ford算法的思路,
用二维数组记录下每两个点的最短距离和路径
"""
import numpy as np
path = [
[0, -1, 3, np.inf, np.inf],
[np.inf, 0, 3, 2, 2],
[np.inf, np.inf, 0, np.inf, np.inf],
[np.inf, 1, 5, 0, np.inf],
[np.inf, np.inf, np.inf, -3, 0]
]
def floyd(matrix):... |
8bb3e0f83c2b1dce6fe268910576ec0a729a78a6 | ageraldo1/Python-bootcamp | /sort/examples.py | 1,331 | 4.40625 | 4 | # example 1 - sort to a new variable - works for any iterable
li = [9, 1, 8, 2, 7, 3, 6, 4, 5]
s_li = sorted(li)
print (li)
print (s_li)
# example 2 - sort in place - only works for list
li.sort()
print (li)
# example 3 - in reverse order
li.sort(reverse=True)
print (li)
# sorting a set
my_set = {8, 4, 99, 8, 4}
pr... |
919a995d7f32c98509c5a70461a520dde694c0f2 | gilbutITbook/006936 | /Unit 38/assertion.py | 190 | 3.796875 | 4 | x = int(input('3의 배수를 입력하세요: '))
assert x % 3 == 0, '3의 배수가 아닙니다.' # 3의 배수가 아니면 예외 발생, 3의 배수이면 그냥 넘어감
print(x)
|
7fe6c1bbef710643b17984a20b66be12528269f6 | manujo-varghese/python_youtube | /dictionary.py | 1,434 | 4.65625 | 5 | # dictionaries are built in data types available with python
# defining dictionaries in python
employee = {'name': 'Joseph', 'age': 30, 'departments': ['Development', 'Testing']}
#print(employee)
# access value by referencing key index
#print(employee['salary'])
# try to access a key which does not exist
#... |
40709ba151d336b2c474c220f21794e30ba1cbfc | manish4005/my_code | /chessQueenpy | 943 | 3.796875 | 4 | #!/usr/bin/python
import sys
# Problem Statement : Find the place of N queen in NxN chess box
# such they do not kill them selves
to_update = 10
queen_pos = [-25,-25,-25,-25]
def isvalid(raw,col):
global queen_pos
#print "checking validation for {0}, {1} and current queen {2}".format(raw,col,queen_pos)
for i in r... |
a4fc5184ee7852022e5b7c75fb6813cd61f3fbdf | TsujiEisho/AOJ | /9_A.py | 226 | 3.515625 | 4 | w = str(input()).lower()
ans = 0
while True:
l = list(input().split())
if l[0] == "END_OF_TEXT":
print(ans)
exit()
else:
for i in l:
if i.lower() == w:
ans += 1
|
48fbf9c3994da39851a48069d56c199fc99c762b | asp2809/Python | /Restaurant Management System/rmswithcalc.py | 10,320 | 3.84375 | 4 | #program for Restaurant Management System with calculator using tkinter
from tkinter import *
import datetime
from math import *
root=Tk()
#frame for the restaurant management part
frame1=Frame(root, width=1000, height=1000, padx=20, pady=20)
#frame for the calculator part
frame2=Frame(root, width=700, height=1000, p... |
137dd19a52cbbfb237ed9b3e3c46e2c05bf47bad | Vinypooh/Python-in-CS3101 | /homework/homework1/homework1_part2.py | 3,399 | 4.4375 | 4 | ###############################################
# COMS3101.001 - Python - Homework 1
#
# Please fill in your solutions for part 2 to 4
# below.
##############################################################################
# Part 2
# For each line in the following interactive Python interpreter session, write
# a sh... |
62d25dda8c93fff76470c112f7fc375916b8ce9a | basilcea/Computer-Architecture | /ls8/cpu.py | 4,549 | 3.578125 | 4 | """CPU functionality."""
import sys
branchTable ={
HALT: halt_op,
PRINT: print_op,
ADD: add_op,
PUSH: push_op,
POP: pop_op,
CALL: call_op,
RET: ret_op
}
# create functions for each activity
def halt_op ():
self.HALT = True
def pop_op():
self.reg[operand_a] = self.ram_read(self.reg... |
060d72e9b79d7bc1e246284365c68d9205bb9768 | Gadhy/trabajo-n-7 | /bucles-iteracion/bi5.py | 328 | 3.671875 | 4 | import os
#DECODIFICAR MENSAJE ENCRIPTADO
#input
msg=os.sys.argv[1].upper()
#bucle
for letra in msg:
if letra=="A":
print("Hola")
if letra =="B":
print("Mi amor")
if letra=="C":
print("Te quiero")
if letra=="D":
print("Mucho")
#fin literador
print("\n")
print("fin del ... |
cf3be12ba8fb292c359d3808d95559d205c364c8 | realcr/sstash | /sstash/tests/test_encode_utils.py | 493 | 3.71875 | 4 | from ..encode_utils import bytes_to_hex_str, hex_str_to_bytes
def test_bytes_str_conversion():
"""
Test the validity of conversion between bytes and hex string.
"""
some_bytes = b'some bytes.'
some_str = bytes_to_hex_str(some_bytes)
some_bytes2 = hex_str_to_bytes(some_str)
some_str2 = bytes... |
96dae1c5f9b447a811040a3f1b33d029a5a0ef72 | CharlieHuang95/Algorithms | /Leetcode/permutations.py | 648 | 3.859375 | 4 | # Permutations
# Given an array of numbers, generate a list of all possible
# permutations. We can assume that there are no duplicates.
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def dfs(path):
if len(p... |
66310f3879bfbabb1fa0284914358a2d67ebe8bc | Babkock/python | /3 - Strings, Basic IO, Operators/strings/strings.py | 1,412 | 4.375 | 4 | #!/usr/bin/python3
#
# Tanner Babcock
# Topic 3 - Strings
# September 3, 2019
string = "Woody Allen in The Passion of Joan of Arc"
# capitalize() capitalizes the first letter in the string,
# and un-capitals all of the others
print(string.capitalize());
# find() returns the index of the given substring,
# or returns... |
e77bce2a0c29a489d6529b5e6b7fca30b79738ac | nukacha/leetcode | /problems/1071.py | 544 | 3.65625 | 4 | def dividable(str1: str, str2: str) -> bool:
return str2 in str1 and str1.replace(str2, '') == ''
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
if len(str1) > len(str2):
short, long = str2, str1
else:
short, long = str1, str2
for i in rang... |
b641cf06d1118924a1ae8c0b2312cf5f5d05389b | Gunjack25/Python | /BuggyCal.py | 865 | 3.59375 | 4 | def main():
x = int(input("Number of test cases b/w 1 to 100"))
Final = []
if x > 0 and x < 101:
for i in range(x):
l = int(input("Enter the first number"))
b = int(input("Enter the second number"))
answer = cal(l, b)
Final.append(answer)
print(Fin... |
a9dfdbe375f48808be40fac7f1334d7d44c03479 | gelexgaray/katas.python | /project_euler/001_sum_multiples_of_3_and_5.py | 1,941 | 4.0625 | 4 | # https://projecteuler.net/problem=1
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
def sum_multiples_of_3_and_5(to_number: int ):
sum_of_values:int = 0
for number in ra... |
87064be3a33022b283af3f53be8dcd64191503cf | freddydavis15/myProjects | /HelloWorld.py | 150 | 4 | 4 | j=5
if j==5 :
print("hai")
elif j<5 :
print("less than 5")
if j==4 :
print("am 4")
else :
print("am anything")
else :
print("i am what am")
|
9d72ad566880dd292f5695c7f3f28a183b2382a7 | yashkoli/python-examples | /insertionsortwithuser.py | 446 | 4.0625 | 4 | def insertionsort(alist):
for index in range(1,len(alist)):
currentvalue=alist[index]
pos=index
while pos>0 and alist[pos]-1 > currentvalue:
alist[pos]=alist[pos -1]
pos=pos-1
alist[pos]=currentvalue
alist=list()
num=input("enter no of element in the list... |
47fcb01195c55293f9f38ec6527df4873f854d92 | guoyuquan/Graduate | /Programming/Python/4ObjectType/other.py | 449 | 3.59375 | 4 | X=set('spam');
Y={'h', 'a', 'm'};
print(X, Y);
print(X & Y);
print(X | Y);
print(X-Y);
print({x**2 for x in [1,2,3,6]});
print(1/3);
print(2/3+1/2);
import decimal;
d=decimal.Decimal('3.141');
print(d+1);
decimal.getcontext().prec=2;
decimal.Decimal('1.00')/decimal.Decimal('3.00');
from fractions import Fraction;
f=Fr... |
c79cf1e9a66198f6fa74a8c1ec3a5df301eb6431 | caiyunz/learning | /instance/try_except.py | 464 | 4.125 | 4 | #!/usr/bin/python3
print("Please input the two number!")
print("If two number's sum is 0 to exit.")
while 1:
try:
first_number=input("Please input the first number:")
second_number=input("Please input the second number:")
number=int(first_number)+int(second_number)
except ValueError:
... |
837723ffaaeb435e0a42f23e380397e145b80f47 | poppindouble/AlgoFun | /construct_the_rectangle.py | 659 | 3.734375 | 4 | import sys
from math import sqrt
class Solution:
# def constructRectangle(self, area):
# root = int(sqrt(area))
# result = sys.maxsize
# resultList = [0] * 2
# for width in range(1,root + 1):
# if area % width == 0:
# height = area // width
# if height - width < result:
# result = height - wid... |
70ab7d8efcb540cbdda13ebc372cbd1e23edb665 | TishinIlia/jobeasy-algorithms-course | /lesson_3/HW_1/Home_Sum_of_digit.py | 741 | 4.125 | 4 | # TODO: Homework: Rewrite a program with any number of digits.
# Instead of 3 digits, you should sum digits up from n digits number,
# Where User enter n manually. n > 0
from random import randint
# n = int(input("Enter a number of digits "))
# n = 5
# digits = 84621
# (10000, 99999)
# down 10 ** 4
# up (10 ** 5)... |
63e51f8ec0c794908dd804b0e53605d567207888 | HelenDeunerFerreira/decimal-numbers-to-binary-numbers | /decimalBinario.py | 215 | 3.515625 | 4 | def dec2bin():
valor = int(input('número pra binário: '))
listaBin = []
while valor > 0:
(valor, numBin) = divmod(valor, 2)
listaBin.insert(0, numBin)
print(listaBin)
dec2bin()
|
8ee52fc12fe3abe78543fd11974f8ea65258d5d9 | nguyenducmanh1206/nguyenducmanh-fundamental-c4e21 | /sisson4.1/baitap1.py | 515 | 3.765625 | 4 | menu={
"ngoc le":"pho",
"quang":"pet le",
"age":"20",
}
while True:
print(menu)
name=input("ban muon thong tin gi ")
if name in menu:
print(menu[name])
else:
m=input("ban co muon bo sung khong(Co, Khong)")
if m == "Co":
n=input("ban muon them gi")
... |
11c0f9122dc5f0dd10149484121ac53237cb3a57 | KristianMSchmidt/Fundamentals-of-computing--Rice-University- | /Interactive Programming/Andet/pig_latin.py | 1,025 | 3.671875 | 4 | ##################################################
# Student should add code where relevant to the following.
import simplegui
# Pig Latin helper function
def pig_latin(word):
"""Returns the (simplified) Pig Latin version of the word."""
first_letter = word[0]
rest_of_word = word[1 : ]
global p
... |
c1fd84930569e424ec6797b33860313de7f13e95 | recuraki/PythonJunkTest | /password/gen.py | 4,132 | 3.65625 | 4 | import string
import random
import secrets
"""
適当なパスワードを作成する generate(length)を提供する
標準では、発音・形状的に間違えやすい以下の文字を使用しません。
oO01IilL9qQZz2dDgGnmNMbB8pPtT
これが不要の場合、ignorechars=set()などで消してください。
使い方:
o = generatePassword()
o.useSpecial = False
o.addIgnore("@")
for i in range(10):
print(o.generate(length=5+i))
"... |
0cc7adced9a328013c3322f6e2de5d3b3f499cf1 | sunshine-mtt/Selenium | /52_week_4.0.py | 980 | 4.03125 | 4 | """
作者:sunshine
功能:52周存钱法
版本:4.0
日期:04/22/2019
4.0 灵活设置每周存款数,增加的存款数及存款周数
"""
import math
def saving_money(total_week, money_value,increase_value):
"""
计算存款金额
"""
saving_value = 0
money_list = [] # 记录每周存款数的列表
for i in range(total_week):
money_list.append(money... |
b4996e24b9bc2ccff45bc30c345954a4659b7388 | savadev/leetcode-solutions-3 | /283. Move Zeroes/283_move_zeros.py | 216 | 3.59375 | 4 | def moveZeroes(nums):
for i in range(len(nums)):
if nums[i]==0:
nums+=[nums.pop(i)]
return nums
nums=[0,1,0,3,12]
print(moveZeroes(nums))
|
d8b7358411aa5177f66f4e201da330b6c2f7a6e7 | HuipengXu/leetcode | /isValidSerialization.py | 1,584 | 3.578125 | 4 | # @Time : 2019/7/21 10:28
# @Author : Xu Huipeng
# @Blog : https://brycexxx.github.io/
import re
class Solution:
def isValidSerialization(self, preorder: str) -> bool:
stack = []
nodes = preorder.split(',')
i = 0
while i < len(nodes):
if len(stack) >= 2 and stac... |
27104daf383a1647b04d23b150f7b47b19e40c2c | JoZonneveld/TCR-python-lessons | /exercises/Jaar 1/1. Introduction to Python/Exercise2.py | 289 | 4.375 | 4 | user_input = ''
# Change `your name` to your own name
while user_input != 'your name':
user_input = input('Voer uw naam in: ')
# Change `your name` to your own name
if user_input == 'your name':
print('this is my name')
else:
print('this is not my name')
|
d7f3102f38a9853e0b458bd0f45a86fecb0db997 | siraiwaqarali/Python-Learning | /Chapter-13/8. any and all function.py | 434 | 4.03125 | 4 | # any and all function
# any function - returns True if there is atleast one True in the list otherwise False
# all function - returns True if all values are True in the list otherwise False
numbers1 = [2, 4, 6, 8, 10]
numbers2 = [1, 2, 3, 4, 5, 6]
# evens1 = []
# for num in numbers1:
# evens1.append(num... |
5e772a7f057886120173e536c667439812923c15 | jhall6226/Principles-of-Computing--Part-1 | /Mini-Projects/Mini Project 1/mini_project1_v1.py | 3,522 | 4.1875 | 4 | """
Merge function for 2048 game.
"""
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
# If the line is length 1, then we cannot merge it. Return the line.
if len(line) == 1:
return line
else:
new_line = []
anchor = 0
... |
e0f3719e7fa522266d95169394d823d3a9298ff2 | mooja/dailyprogrammer | /challenge162easy.py | 1,312 | 3.828125 | 4 | #!/usr/bin/env python
# encoding: utf-8
# Daily Programmer Challenge 162 Easy
#
# https://www.reddit.com/r/dailyprogrammer/comments/25clki/5122014_challenge_162_easy_novel_compression_pt_1/
#
# January.01.2016
import re
def decode(dict, encoded_text):
output = []
chunks = encoded_text.split()
for chun... |
48503aeae0ccd68fb24958d2c87ef817c8bd7a00 | JKHila/baekjoon-practice | /etc/4999 - Ah!.py | 225 | 3.578125 | 4 | N = raw_input()
M = raw_input()
n=0
m=0
for i in N:
if i != 'h':
n += 1
else:
break
for i in M:
if i != 'h':
m += 1
else:
break
if n >= m:
print "go"
else:
print "no"
|
f6ead504447c13970a5763eab321f683251fec3b | liuzhijielzj/python-tutorial | /json_test/remember_me.py | 514 | 3.84375 | 4 | import json_test
# Load the username, if it has been stored previously.
# Otherwise, prompt for the username and store it.
filename = 'username.json_test'
try:
with open(filename, 'r') as f_obj:
username = json_test.load(f_obj)
except FileNotFoundError:
username = input("What is your name? ")
with ... |
e69ff7221ff7cabc5da799c3198c4c75142876db | victorradael/learning_python | /dictionaries.py | 417 | 4.125 | 4 | myList = [1, 2, 3]
print(myList[1])
myDic = {'chave':1.2, 'chave2': 'string'}
print(myDic)
print(myDic['chave2'])
print(myDic['chave2'].upper())
# Depois e tudo normal como uma string comum
# Muito similiar ao objeto ou JSON
myDic['chave2'] = 'mudei'
print(myDic)
# Metodos
print(myDic.keys())
print(myDic.keys()[0... |
60f654fe607ad7bb22463d5c0eb764828db3d463 | shavkat1717/dastur.uz_1000_ta_masala_05 | /16_masala.py | 442 | 3.515625 | 4 | onliklar=["Yigirma","O'ttiz","Qirq","Ellik","Oltmish"]
birliklar=["bir","ikki","uch","to'rt","besh","olti","yetti","sakkiz","to'qqiz"]
x=int(input("[20;69] oraliqda istalgan yoshni kiriting: => "))
import math
a=math.floor(x/10)
q=x-a*10
if x>=20 and x<70:
if x%10!=0:
print(f"{onliklar[a-2]} {birlik... |
5433a8e57b5c57de31e4de44790e45dfa2311fd2 | igimot/learning | /Python/2w/5.py | 1,184 | 4.09375 | 4 | poseOne1 = int(input())
poseOne2 = int(input())
poseTwo1 = int(input())
poseTwo2 = int(input())
''' если первое число меньше вторых '''
if poseOne1 > poseTwo1 or poseOne2 > poseTwo2:
''' проверяем если разница более 1 тогда НЕТ '''
#if (poseOne1 - poseTwo2 == 1 or poseOne2 - poseTwo1 == 1) or ( poseTwo2 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.