blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
04aaf13451a57095c77bce7a89ce16be0fd1a425 | mdanlowski/algorithms | /SortingAlgorithms/merge_sort.py | 510 | 3.71875 | 4 | def merge_sort(arr):
d = int(round(len(arr)/2))
if len(arr) < 2: return arr
larr = arr[:d]
rarr = arr[d:]
larr = merge_sort(larr)
rarr = merge_sort(rarr)
return merge(larr, rarr)
def merge(l, r):
ret_arr = []
while len(l) > 0 and len(r) > 0:
if l[0] <... |
815d8b2b9b4431acea15025f48fe3f0d175bea9e | simonxu14/LeetCode_Simon | /14.Longest Common Prefix/main.py | 710 | 3.625 | 4 | #coding = utf-8
class Solution(object):
def longestCommonPrefix(self, strs):
length = len(strs)
if length == 0:
return ""
elif length == 1:
return strs[0]
else:
result = strs[0]
for i in range(1, length):
if strs[i] == "... |
7d6088c5b27834e9b49c1c7b3c9d3aa5da6b5830 | DayGitH/Python-Challenges | /DailyProgrammer/DP20130510C.py | 7,377 | 3.9375 | 4 | """
[05/10/13] Challenge #123 [Hard] Robot Jousting
https://www.reddit.com/r/dailyprogrammer/comments/1ej32w/051013_challenge_123_hard_robot_jousting/
# [](#HardIcon) *(Hard)*: Robot Jousting
You are an expert in the new and exciting field of *Robot Jousting*! Yes, you read that right: robots that charge one
another ... |
8838773927bfd9a5083b638551d2b657521a3255 | shortdistance/workdir | /python高级编程code/ch03/p077.py | 239 | 3.5625 | 4 | def method(self):
return 1
klass = type('MyClass', (object,), {'method': method})
instance = klass()
print instance.method()
class MyClass(object):
def method(self):
return 1
instance = MyClass()
print instance.method()
|
924cca595add04f56a3dceebb9c9d3e7d22a3b35 | GrowingDiary/python-exercises | /src/008.py | 647 | 3.859375 | 4 | # !/usr/bin/python3
# -- coding: utf-8 --
"""
题目:输出 9 * 9 乘法口诀表。
"""
def solution1():
for i in range(1, 10):
for j in range(1, i + 1):
print('{j} x {i} = {k}'.format(i=i, j=j, k=i * j), end=', ')
print('')
def solution2():
line_list = []
for i in range(1, 10):
line_li... |
8632951593e5f17f39bd4365f092bea2318f72ba | lawun330/Python_Basics | /password enterer.py | 542 | 3.5 | 4 | #Calling function with several Arguments
def passwords(string,Trials=4,b='Try again\n'):
while True:
key=input(string)
if key in ('www,zzz'):
print("Unlocked!")
return True
else:
print(b)
Trials-=1
if Trials<0:
rais... |
63035b556a4f8e183f14dd503ca3e47f47c1f5cc | NeonNingen/allpythonprojects | /ClassPractice2.py | 1,204 | 3.78125 | 4 | class Account:
def __init__(self, accountNumber, openingDate, currentBalance, interestRate):
self.accountNumber = accountNumber
self.openingDate = openingDate
self.currentBalance = currentBalance
self.interestRate = interestRate
def getAccountNumber(self):
return self.ac... |
184bb78b2672d60edfba52ec276ba3143e034dc1 | Arslan0510/learn-basic-python | /7loops.py | 496 | 3.703125 | 4 |
users = ['Ali', 'Jamal', 'Danish', 'Zeba', 'Waqar', 'Qirat']
# name = list('Edwin')
# print(name)
my_list = list(range(0, 10))
print(my_list)
# For loop
for user in users:
print(user)
for i in range(0, 20):
print('I run 20 times')
name = 'Edwin'
for letter in name:
print(letter)
... |
3feab6e62584e97c818818249caaef68ee7100d8 | chowdhuryRakibul/algorithms | /StableMariages.py | 3,960 | 3.84375 | 4 | '''
Write a Python function stableMatching(n, menPreferences, womenPreferences) that gets the number n of women and men, preferences of all women and men, and outputs a stable matching.
The function should return a list of length n, where ith element is the number of woman chosen for the man number i.
'''
def stableMa... |
a7fb912bffbde3091691667bf97446914c975718 | kondil/Python | /101_Openpyxl/read_xlsx.py | 1,122 | 4.0625 | 4 | #!/usr/bin/env python
# This is a tutorial on how to read an xlsx Workbook using the Openpyxl library.
# Let's read from a current excel file.
# - For this we will need to load 'load_workbook' from openpyxl.
from openpyxl import load_workbook
wb = load_workbook(filename='tmp.xlsx', read_only=True)
# In order to disco... |
df4c52b518cef274c3f794a56c941933ec371251 | Niranjanmd/Python | /Numbers.py | 680 | 3.96875 | 4 | x= 1 # int
x = 1.1 #float
x= 1+1j # a+bi --i is imaginary
print(10/3)
print(10//3) # to get the intiger use double //
print(10+2)
print(10-2)
print(10*2)
print(10%3)
print( 10**3) # 10 to power 3
# Function to work with Number
print(round(2.9)) # to round the number to nearest digit
print(abs(-2)) # ... |
9028674a05fbb8e43677c4f9d2608b08212745a9 | PemLer/Journey_of_Algorithm | /leetcode/001-100/T86_partition.py | 798 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
if head == N... |
8f94512eb96bb70dfd4d62d7bf2b39c1dd235192 | DevShasa/code-challenges | /codewars/binary_sum.py | 227 | 4.21875 | 4 | '''
Implement a function that adds two numbers together
and returns their sum in binary
The conversion can happen before or after the addition
'''
def add_binary(a, b):
return str(bin(a+b))[2:]
print(add_binary(51,12)) |
623a3664c71e4431de7ebdf82d91515c7287440d | cmmccolgan/hackbright | /Review/Typecasting.py | 678 | 4.0625 | 4 | '''
Reviewing Typecasting
#1 = 6.0
number_1 = float(6)
print type (number_1)
print float(number_1)
#2 = "6"
number_2 = str(6)
print type (number_2)
print str(number_2)
#3 =8
number_3 = int(8.999)
print type (number_3)
print int(number_3)
#4 ="8.999"
number_4 = str(8.999)
print type(number_4)
print str(number_4)
#5... |
e835b26d4bb838d88b15519924b3eaafb5ae005c | ahamedbasha-n/dice-simulator | /Dice Simulator/dice_simulator.py | 1,432 | 4.1875 | 4 | """
Aim - Identify the Algorithm and Develop a dice simulator.
Algorithm:
1. Import Random Package.
2. Create a condition for Looping within the range of 1 to 6.
3. Print the Face.
"""
#Solution:
import random
print("Welcome to My Dice Simulator.")
x="y"
while x=="y":
number=random.randint(1,6)
... |
2fa81b7780a6eaa4c95e6a38ad510118543e91ec | WalterVetrivel/iit_python_sqlite3 | /read_sqlite3_database.py | 770 | 4.09375 | 4 | # Import the built-in sqlite3 module
import sqlite3
# Global constants
DATABASE_NAME = 'astronaut.db'
TABLE_NAME = 'tblAstronaut'
# Creating a database connection
connection = sqlite3.connect(DATABASE_NAME)
# Creating cursor to interact with database via the connection
cursor = connection.cursor()
# Select query
se... |
3489579e1a8edb550e8fb0d936855860a3355bc8 | fadhilmulyono/CP1401 | /CP1401Lab6/CP1401_Fadhil_Lab6_3.py | 504 | 4.15625 | 4 | '''
A restaurant is offering meals at 50% discount. Write a program that reads in the cost of the meal and displays a receipt. An example is as follows:
Enter meal amount ($): 120
Receipt
Cost of meal: $120
50% discount: $60.0
Total amount: $60.0
'''
def main():
meal = float (input("Enter meal amount ($)... |
96fc50f4fc4b1758d910f798e690b68a9f19b62f | micropop1989/python-file | /class1.py | 663 | 3.703125 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
#method #2
def printname(self):
print(self.name, self.age)
#3
class Student(Person):
pass
#4
class Student2(Person):
def __init__(self, name, age, year):
super().__init__(name, age)
se... |
577611b8e200dffed77a61d7214575c068d2d7f2 | Leputa/Leetcode | /python/337.House Robber III.py | 1,564 | 3.6875 | 4 | #import queue
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# class Solution:
# def rob(self, root):
# """
# :type root: TreeNode
# :rtype: int
# """
# if(root==None):
# return 0
#... |
03b1ce3886ea3520cc81ac59df5506c35f954d95 | Iararibeiro/coding-challenges | /misc/isunique.py | 314 | 3.8125 | 4 | def solution(word):
occurency = [False] * (25)
result = True
for letter in word:
position= ord(letter) - 97
if occurency[position] == False:
occurency[position] = True
else:
result = False
return result
print solution("abc")
print solution("casa")
#print solution("116")
#print solution("146")
|
e3130c6ca80def91e844303cd6b031675f3529dd | Pandara320/Scratch | /python-achieved/py-cs1/Assignment3_1.py | 175 | 3.9375 | 4 | hrs = input("Enter Hours: ")
h = float(hrs)
rate = input("Enter rate: ")
r = float(rate)
if hrs > 40 :
payment = 40*r+(h-40)*(1.5*r)
else:
payment = h*r
print (payment)
|
2e6d29b325aef6ede779fd712569b60354d4b70d | nazriel/Daily-Coding-Problem | /day-1/solution.py | 1,331 | 3.90625 | 4 | #!/usr/bin/env python3
import unittest
def does_adds_up(numbers_list: list, sum: int) -> bool:
"""
Check whenever any two numbers provided in numbers_list adds up to sum.
"""
subs = set()
# O(n)
for number in numbers_list:
if number in subs: # O(1)
return True
sub... |
8a3f68cf6a18abfbe26b1d042d5935bef3beffc5 | RosTS26/Pyton | /adreslist/adreslist.py | 1,752 | 3.875 | 4 | import pickle
class idlist():
"""Данные людей"""
q = True
N = 0
def __init__(self):
print('\nВведите имя, адрес и номер телефона человека.')
print('Для завершения списка, введите в поле для ИМЕНИ " - "')
self.name = input('\nВведите имя: ')
if self.name == '-':
idlist.q = False
else:
pass
if id... |
efda470bbe6d7e535aeb9f0bcb128cfcd9cd2e6e | naliwajek/tdd-pair-kata2 | /python/tennis.py | 1,914 | 3.65625 | 4 | # -*- coding: utf-8 -*-
class Player:
def __init__(self, name):
self.name = name
self.points = 0
def win_point(self):
self.points += 1
def won_with(self, other_player):
return self.points >= 4 and other_player.points >= 0 and \
(self.points - other_player.poin... |
b6a2e8f7ca2bba5c45cac7e2453dc95d87163a8a | taxioo/study_python | /01.python/ch16/ex04-2.py | 1,801 | 3.609375 | 4 | class NameCard:
def __init__(self, name, email, phone, address):
self.name = name
self.email = email
self.phone = phone
self.address = address
def print(self):
print(f'{self.name}, {self.email}, {self.phone}, {self.address}')
class AddressBook:
def __init__(self):
... |
6c02928ba0a1227a65289b94d068f1ca5c44eb30 | 1572903465/PythonProjects | /test/venv/threading/thrading_01.py | 456 | 3.609375 | 4 | import threading
import time
number = 0
lock = threading.Lock()
def plus():
global number
lock.acquire()
for i in range(1000000):
number+=1
print("When its completes,number = ",(threading.current_thread().getName(),number))
lock.release()
if __name__ == '__main__':
for i in range(2):... |
b556d5a293b1949464559b13b4b0176f5d87f70c | jeremyosborne/python | /general/csv2table/csv2sql.py | 10,575 | 4.34375 | 4 | """Convert a csv file to an sqlite table."""
import sys
import csv
import sqlite3
import os
import re
# pointer to our csv file descriptor
csvFile = None
columnNames = None
columnTypes = None
columnComments = None
validDataTypes = ["string", "number", "date"]
idColumnName = "_id"
outfileName = None
ou... |
c9320fdc2e5be92878fffe7d072a4234ff48cf59 | axelthorstein/university-projects | /Old Classes/Computer Science/108/Python/random_story_generator.py | 2,215 | 3.703125 | 4 | import random
def random_story_generator(training_file, context_length, story_length):
""" (open file, int, int) -> str
Return a somewhat randomly generated text using the words from the
original story.
>>> random_story_generator('And the fan, and the cup, and the ship, and the fish', 2, 11)... |
a1914624fab0c64f8704cc237c3412d4906aae10 | kylemcgourty/Algorithms | /Chapter 5.5.py | 4,596 | 3.703125 | 4 | #Chapter 5.5
#5.5.1
answer = """
Codes 3 and 4 are prefix-free and uniquely decodeable.
Code 3 decoding: A.
Code 4 decoding: ADDDD
"""
#5.5.2
answer = "Uniquely decodeable but not prefix free: 1, 10"
#5.5.3
answer = "0011, 011, 11, 1110"
#5.5.4
answer = "The first example is not uniquely decodeable. Let A = 1... |
55b4f2fd32ce416f5df8ab4a056ea45df2c39a37 | moonhyeji/Python | /Python01/com/test02/testfortest.py | 476 | 4.0625 | 4 | # -*- coding:utf-8 -*-
a = set(['1','2','3','a','b','c']) #list : [] 순서잇는집합 중복있음 #set():순서없고 중복없음
b = {'a','b','c','d','e','f'} # dict {} :키 중복불가 .값 중복가능. 순서없음
print(a.intersection(b))
#a b 의 교집합을 출력해라.
print(type(b))
'''
[] 대괄호는 리스트
() 소괄호는 튜플
{ } 중괄호는 딕셔너리 그리고 집합(set)에서 사용됩니다.
'... |
45d6c7fe87645afc063e915076f984ca0174fa85 | sssv587/PythonFullStackStudy | /day05_strmenthod/string_method.py | 1,289 | 3.71875 | 4 | # 字符串的内建函数:声明一个字符串,默认可以调用内建函数(准备好的一些函数)
# 第一部分:大小写
# capitalize() title() istitle() upper() isupper() lower() islower()
# message = 'zhaorui is a beautiful girl!'
# msg = message.capitalize() # 将字符串额第一个字符转成大写的表示形式
# print(msg)
# msg = message.title() # 将字符串的每个单词的首字母大写
# print(msg)
# result = message.istitle() #... |
1112eab572c5eff4132c38c334024422b46b7246 | belono/python-escpos | /src/escpos/katakana.py | 2,481 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""Helpers to encode Japanese characters.
I doubt that this currently works correctly.
"""
try:
import jaconv
except ImportError:
jaconv = None
def encode_katakana(text):
"""I don't think this quite works yet."""
encoded = []
for char in text:
if jaconv:
... |
3243533c5331ee26ad2ea60000b161bbd3464560 | higustave-ops/DSAA | /create_file.py | 808 | 3.75 | 4 | """Create a file"""
def create_file(data, sort_choice):
"""Function to create a file"""
file_name = str(f'order_by_{sort_choice}.txt')
try:
with open(file_name, 'w') as final_text:
final_text_str =''
for element in data:
sequence = element['sequence']
... |
220758b443ee6bc8cf108715b9036f893b9df8cc | Lab-Work/IDOT-SmartWorkzone | /Cross_Evaluation/src/EnKF.py | 7,011 | 3.734375 | 4 | import numpy as np
from copy import deepcopy
__author__ = 'Yanning Li'
"""
This is the abstract Ensemble Kalman filter class. It contains the necessary components for the iteration of
the EnKF. For each specific problem, the user need to create a subclass and overwrite functions for the state evolution equations
and t... |
99796fd8d75489659cde3606ea23c2bc25af77ba | diegoaspinwall/Unit-2 | /gradeCalculator.py | 310 | 4.15625 | 4 | #Diego Aspinwall
#9-13-17
#gradeCalculator.py
grade = float(input('Input your grade: '))
if 100>grade>=90:
print('You earned an A')
elif 90>grade>=80:
print('You earned a B')
elif 80>grade>=70:
print('You earned a C')
elif 70>grade>=60:
print('You earned a D')
if grade<60:
print('You earned an F') |
83a1c2f04d0081e6210725c19d868982250365d8 | RamnathShanbhag/APS-2020 | /sum_of_even_fibonacci.py | 321 | 3.96875 | 4 | def sum_fibonacci(n):
if (n < 2) :
return 0
ef1 = 0
ef2 = 2
sm= ef1 + ef2
while (ef2 <= n) :
ef3 = 4 * ef2 + ef1
if (ef3 > n) :
break
ef1 = ef2
ef2 = ef3
sm = sm + ef2
return sm
n=int(input())
res=sum_fibonacci(n)
print(res)... |
f1dd8c231a92db360cfadd92deeb7a1867adbf30 | sandip308/python-program-for-beginners | /N natural number in reverse.py | 85 | 3.875 | 4 | x= int(input("Enter a number"))
count=1
while(x>=count):
print(x)
x=x-1
|
692c0d7ba2331df5365cee52ec8c311e8e54ca63 | Lynch08/MyWorkpands | /Code/Messingaround/vampire.py | 205 | 3.859375 | 4 | name = ('Enda')
age = 3000
if name == 'Alice':
print ('Hi Alice')
elif age < 12:
print ('not Alice kiddo!')
elif age > 2000:
print ('nah your a vamp!')
elif age > 100:
print ('hey granma!') |
7ff22f568966cd0fffa6561a0662ce079b57faaa | Gangamagadum98/Python-Programs | /PythonClass/LearningEncapsule.py | 163 | 3.578125 | 4 |
class Actor:
name="abc"
def __init__(self):
self.age=45
def acting(self):
print("best dancer")
act=Actor()
print(act.name)
|
fd428274bff96ecb3050f07584c63f24db75ee3d | IniOluwa/Fellowship | /Proctor/binary.py | 450 | 4.4375 | 4 | # Create a function called binary_converter. Inside the function,
# implement an algorithm to convert decimal numbers between 0 and 255 to
# their binary equivalents.
# For any invalid input, return string Invalid input
# Example: For number 5 return string 101
def binary_converter(number):
if number < 0 or num... |
1fda663f117c9590060cf1d5531e3cb6201ce434 | jiepy/byte | /ext/pysmtp_v1.py | 1,059 | 3.515625 | 4 | #!/usr/bin/env python
# ---------------------------------------
# author : Geng Jie
# email : gengjie@outlook.com
#
# Create Time: 2016/3/13 15:21
# ----------------------------------------
# 本程序只是实现了简单的认证发信
# 基本思路是连接服务器,认证,发信
# 需要定义邮件相关信息
# ########################################
import smtplib
# 定义邮件服务器地址以及端口
SMTP... |
7e72eba28b88efbad613e9dcfd320c81b16cdbc0 | sarski/6.00.1x | /ProblemSet1/PS1 Problem 2.py | 148 | 3.953125 | 4 | word = 'bob'
count = 0
for idx in range(len(s)):
if s[idx: (idx + 3)] == word:
count += 1
print 'Number of times bob occurs is: ', count |
a0946f334eae002ed01c9a1bcfd6ca48c8db193f | pliniusblah/Pyhton_IME | /S7/S7-T2.py | 335 | 4.09375 | 4 | largura = int(input("digite a largura: "))
altura = int(input("digite a altura: "))
n = largura
m = altura
while altura > 0:
while largura > 0:
if(altura == 1 or altura == m or largura == 1 or largura == n) :
print("#", end = "")
else:
print("", end = " ")
largura -= 1
print()
largura = ... |
642a0c4530e4735395ee1e31ffd0b4d06a72d5bc | uuchey/battleship | /battleship_game/battleship.py | 3,676 | 3.875 | 4 | import copy
# creating an empty list to store a grid
grid = []
# creating an empty dictionary to store the ships
ships = {}
def new_game(grid_width, grid_height):
# adding rows
for i in range(grid_height):
grid.append([])
# adding columns with clear water mark '~' at each place
for j ... |
dfa90774fceac21876470bdfe0eadbc6e4e3e4b7 | XiaoqinLI/Element-design-of-software | /TestBinaryTree.py | 8,141 | 3.953125 | 4 | ## File: TestBinaryTree.py
## Description: we will be adding to the classes Node and Tree that we developed in class
## and testing them. There are several short methods that we will
## have to write. We will create several trees and show convincingly
## that our methods are w... |
ffb54ad8aac924e42081cb5fcaf87aa95d343938 | greatertomi/Python-Algorithms-DataStructure | /data-structures/lists/singly-linked-list.py | 3,210 | 3.796875 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def append(self, value):
new_node = Node(value)
if self.head is None:
self.head = new_node
return
... |
993ce21b534c08711c5c6327643baab9e1b51853 | jhonnyelhelou91/ProjectEuler | /1 - Multiples of 3 and 5.py | 432 | 3.8125 | 4 | def gcd(a, b):
if (b == 0):
return a
return gcd(b, a % b)
def lcm(a, b):
return (int)(a * b / gcd(a, b))
_max = 1000
_a = 3
_b = 5
_lcm = lcm(_a, _b)
res = 0
# add multiples of a
for num in range(_a, _max, _a):
res += num
# add multiples of b
for num in range(_b, _max, _b):
res += num
# ... |
c08ef1c7aff6031c917689e69e6e578bc5e75f27 | kpicott/bttbalumni | /www.bttbalumni.ca/cgi-bin/pages/bttbSoon.py | 1,764 | 3.5 | 4 | """
Web page that hints at things to come
"""
from bttbPage import bttbPage
__all__ = ['bttbSoon']
class bttbSoon(bttbPage):
'''Class that generates the "coming soon" page'''
def __init__(self):
'''Set up the page'''
bttbPage.__init__(self)
def title(self):
''':return: The page ti... |
c162c6822eea7edd76173ce9193d21773e9fbf85 | iopkelvin/CS229 | /ps1/src/featuremaps/featuremap.py | 4,643 | 3.671875 | 4 | import util
import numpy as np
import matplotlib.pyplot as plt
np.seterr(all='raise')
factor = 2.0
class LinearModel(object):
"""Base class for linear models."""
def __init__(self, theta=None):
"""
Args:
theta: Weights vector for the model.
"""
self.theta = theta... |
e4a0ef46d824f291a763882350dfd9db21a8452b | hugoleeney/leetcode_problems | /p199_binary_tree_right_sight_view.py | 1,170 | 3.984375 | 4 | """
199. Binary Tree Right Side View
Difficulty: medium
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <--... |
80ca95719eefa8e661c8cca3b6803928fbffaba6 | enigmer2/Python-www.sololearn.com-www.intuit.ru | /while.py | 64 | 3.515625 | 4 | s = "abcdefghijklmnop"
while s != "":
print (s)
s = s[1:-1]
|
1879b708c88c722a5565bce3e9237816f488d052 | suryaatevellore/AlgorithmicThinking | /RandomGraphs.py | 1,750 | 3.90625 | 4 |
from __future__ import division
import random
from matplotlib import pyplot as plt
def generate_random_graph(nodes,p):
digraph = {}
for node in nodes:
digraph[node]=set([])
remaining_nodes = set(nodes) - set([node])
for next_in_line in remaining_nodes:
if random.random()... |
97a45fb1f5f446075f886c6d54d7f7efeaf0a5c6 | divinelee/data-analysis-combat | /04/04_demo09.py | 141 | 3.53125 | 4 | # 统计函数 统计数组中的标准差 std()、方差 var()
import numpy as np
a = np.array([1,2,3,4])
print(np.std(a))
print(np.var(a)) |
05c6c2f7fc7bf3e13d3c60a17925e266db55e2e9 | p3ngwen/open-notes | /Intro to CS with Python/src/solutions/answer1205a.py | 283 | 3.546875 | 4 | MAXNUM = 100
numbers = list( range(2,MAXNUM+1) )
i = 0
while i < len( numbers ):
j = i+1
while j < len( numbers ):
if numbers[j]%numbers[i]:
j += 1
else:
numbers.pop(j)
i += 1
for i in numbers:
print( i, end=" " )
|
d62f865033b838c67ef76b3b0eaefdb7eea57678 | MysteriousSonOfGod/GUIEx | /JumpToPython/test004(딕셔너리).py | 676 | 3.8125 | 4 | # 딕셔너리 = 연관 배열, 해시같은 대응 관계를 나타내는 자료형, key와 value 한쌍으로 갖는 자료형
# = {key1:Value1, key2:Value2, key3:Value3, .......}
# dix = {'name':'pey', 'phone':'0119993323', 'birth':'1118'}
a = {1: 'a'}
a[2] = 'b'
print(a)
a['name'] = 'pey'
print(a)
a[3] = [1, 2, 3]
print(a)
del a[1] # key = 1 인 key:value 삭제
print(a)
print(a.get(... |
c866e2eb5b0ebf1b9d7ece5400dd17b6543e4c41 | TheVibration/pythonprocedures | /factorialrec.py | 427 | 4.40625 | 4 | # Using recursion by creating a factorial
# procedure. Recursion has a base case and
# a recursive case which is defined almost
# as itself.
# The base case is when n = 0 which makes
# factorial(0) = 1.
# The recursive case is a smaller version
# of itself.
def factorial(n):
if n == 0:
return 1
else... |
6b36dafd41fb1fdea3d78588b2cc4c73882ab9ab | Matheus-Morais/Atividades_treino | /Python Brasil/Estrutura de Decisão/9.py | 528 | 4.125 | 4 | n1 = float(input('Insira um numero:'))
n2 = float(input('Insira um numero:'))
n3 = float(input('Insira um numero:'))
if n1 > n2 > n3 and n1 > n3:
print(n1)
print(n2)
print(n3)
elif n1 > n2 and n1 > n3 > n2:
print(n1)
print(n3)
print(n2)
elif n2 > n1 > n3 and n2 > n3:
print(n2)
print(n1)... |
50b1e5e598ec042cd656526f3dcf585ae6e68a38 | akiraboy/python_20191010 | /collections_tbier/zad_7.py | 238 | 3.515625 | 4 | napis = input("POdaj ciag znaków: ")
samogloski = ['a', 'e', 'i', 'o', 'u', 'y']
ile_samoglosek = 0
for znak in napis:
if znak in samogloski:
ile_samoglosek += 1
print(f"Znaleziono samoglosek: {ile_samoglosek}") |
74c10173f69c75b288904107e4f78c54693610dc | arnabs542/Data-Structures-And-Algorithms | /Sorting/Kth Smallest Element in the Array.py | 1,176 | 3.765625 | 4 | """
Kth Smallest Element in the Array
Problem Description
Find the Bth smallest element in given array A . NOTE: Users should try to solve it in <= B swaps.
Problem Constraints
1 <= |A| <= 100000 1 <= B <= |A|
Input Format
First argument is vector A. Second argument is integer B.
Output Format
Return the ... |
7242420ef63a88413f796e63827a406c53420271 | ArvindSinghRawat/MusicRecommender | /Array.py | 66 | 3.6875 | 4 | a = list([1,2,3,4,5,6,7])
print(a)
for i in a:
print(i,end='') |
b6e8ecf6f30ae17eac371fc45d6ab11dac91763b | syurskyi/Python_Topics | /045_functions/_examples/Python-from-Zero-to-Hero/04-Функции и модули/10-ДЗ-Игра в палочки_solution.py | 1,351 | 3.953125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
number_of_sticks = 10
player_turn = 1
while number_of_sticks > 0 :
print(f'How many sticks you take? Remaining {number_of_sticks}')
taken = int(input())
if taken < 1 or taken > 3:
print(f'You tried to take {taken}. Allowed to take 1, 2, 3 stick... |
2454885aacdc70f944c05f55d5846cbf3521b051 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/space-age/0a61e379cc744126a6d10497ebba7221.py | 1,028 | 3.671875 | 4 | earth_year_ratio = {
"earth": 1,
"mercury": 0.2408467,
"venus": 0.6159726,
"mars": 1.8808158,
"jupiter": 11.862615,
"saturn": 29.447498,
"uranus": 84.016846,
"neptune": 164.79132,
}
SECONDS_PER_EARTH_YEAR = 365.25 * 60 * 60 * 24
class SpaceAge():
def __init__(self, seconds... |
db071e1de0d9822b789a52921e88b2d129cbb884 | tssutha/Learnpy | /list.py | 6,030 | 3.640625 | 4 | import random
import time
from bisect import bisect_left
#sum of nested list
def sumof_nestedlist(ls, nls):
"""
Get the sum of nested list contains integer
"""
for li in ls:
if isinstance(li, (list)):
sumof_nestedlist(li, nls)
else:
nls.append(li)
#print "Final %r" % nls
return sum(nls)
numlist... |
ec6462639ef720e15bfba80adbd5fde412757aab | nrohankar29/Python | /Binary_tree_from_lists_of_list.py | 1,623 | 3.5 | 4 | def testEqual(actual, expected):
if type(expected) == type(1):
# they're integers, so check if exactly the same
if actual == expected:
print('Pass')
return True
elif type(expected) == type(1.11):
# a float is expected, so just check if it's very close, to allow fo... |
c05634267ed550c04cd325fd3ad36f5fafeee713 | vishalkallem/Python-Scripts | /delete_mail.py | 1,381 | 3.8125 | 4 | __author__ = 'Vishal'
import imaplib
'''
Simple script that delete emails from a given sender
params:
-username: Gmail username
-pw: gmail pw
-label: If you have a label that holds the emails, specify here
-sender: the target sender you want to delete
usage: python delete_emails.py
see http://stackove... |
e7e8278a4966e6e378629f9fdde1cbd0cbdde846 | VBharwani2001/Python-Bootcamp | /Day 24/snake.py | 1,284 | 3.984375 | 4 | from turtle import *
start_position = [(0, 0), (-20, 0), (-40, 0)]
class Snake:
def __init__(self):
self.turtles = []
self.create_snake()
self.head = self.turtles[0]
def create_snake(self):
for position in start_position:
self.add_snake(position)
def add_snake... |
c3e85aa04aa8a682db9c6b499d52f728ed211d30 | woosanguk-git/python_study | /control_statement/filter_example.py | 289 | 4 | 4 | # filter()는 시퀀스의 항목들 중 함수조건이 참인 항목만 추출해서 구성된 시퀀스를 반화한다.
def f(x):
return x % 2 != 0 and x % 3 != 0
if __name__ == "__main__":
print(f(17))
print(f(33))
l = list(filter(f, range(2,25)))
print(l)
|
a0352327c52ef1ef72f590620c8a689231c8b94c | devfuner/intro2 | /hangman/hangman_01.py | 1,525 | 3.546875 | 4 | import sys
import random
HANGMAN_PICS = ['''
+---+
|
|
|
===''', '''
+---+
O |
|
|
===''', '''
+---+
O |
| |
|
===''', '''
+---+
O |
/| |
|
===''', '''
+---+
O |
/|\ |
|
===''', '''
+---+
O |
/|\ |
/ ... |
71eea25af8d634916557c17cf56563b912ffa58c | dhivyasa/firefighters | /firefighters/city.py | 3,986 | 3.890625 | 4 | from abc import ABC, abstractmethod
from typing import List
from firefighters.building import Building, BuildingImpl
from firefighters.city_node import CityNode
from firefighters.exceptions import InvalidDimensionException, OutOfCityBoundsException
from firefighters.fire_station import FireStation
class City(ABC):
... |
a45cff8504fe49ebadb78bee641eb74aa4fc80f5 | gotgith/Algorithms | /Algorithms-master/chapter_07_graph/component.py | 1,242 | 3.609375 | 4 | '''
计算连通分量
每一次深度优先遍历都会把所有相连接的节点遍历一遍,用来求连通分量
'''
class Component:
"""Only for dense graph"""
def __init__(self, graph):
self._graph = graph
#是否被访问过
self._visited = [False] * graph.V()
#连通分量
self._ccount = 0
#俩个点是否相连,相连的节点id相同,在同一个连通分量里面
self._id = [-1] * gr... |
1f8f86faa9139b2a6a279f1fe0f94244b180f010 | Ressull250/code_practice | /part2/33.py | 600 | 3.59375 | 4 | import sys
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l,r = 0,len(nums)-1
while l<=r:
mid = l+(r-l)//2
num = nums[mid] if (target<nums[0]) == (nums[mid]<nums[0]) \
... |
37e489e52f93355c3ee7a1fd3fc5cfb91fd6a704 | ac4lyphe/MCE310-Fall-2021 | /Puzzle1.py | 498 | 3.8125 | 4 | """
Write a function to solve the following problem:
You are given two lists and a target value. Write an algorithm that determines if there is a value from each list that the sum is the target value. return True if there is, if not then return False.
"""
list_1 = [0, ... 1] # 100 Million list items
list_2 = [0, ...... |
7f7343a96f48e698c18a22d52709ddd91569da3e | smoonmare/backtrack_sudoku | /backtrack-algo-sudoku-solver.py | 5,246 | 3.8125 | 4 | import turtle
from random import randint
from time import sleep
from turtle import hideturtle
grid = []
grid.append([0, 0, 0, 0, 0, 7, 5, 3, 0])
grid.append([0, 0, 4, 0, 0, 0, 1, 0, 0])
grid.append([3, 8, 0, 6, 0, 0, 0, 0, 7])
grid.append([4, 0, 0, 0, 0, 2, 0, 0, 5])
grid.append([0, 9, 0, 8, 3, 6, 0, 7, 0])
... |
7354b8882bfb362525699cecd0f8e2f79809751d | fxy1018/Leetcode | /112_Path_Sum.py | 1,426 | 3.921875 | 4 | """
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
"""
'''
Created on Jan 15, 2017
@author: fanxueyi
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.va... |
c929b3a7819e5d1b8b6952ab4813df2de9109cbd | conzmr/Compilators | /Partial1/balanced_parentheses.py | 528 | 3.84375 | 4 | import sys
def main():
parentheses = sys.argv[1]
stack = []
char_num = 0
for parenthesis in parentheses:
if parenthesis == '(':
stack.append(parenthesis)
if parenthesis == ')':
if len(stack) == 0 or stack[len(stack)-1] != '(':
print("No balanceado... |
554545adf5875abdaf9d4227ed6cc3456ac34513 | rajtilakls2510/Pandas2 | /Gradient Descent/linear_regression.py | 4,259 | 4.03125 | 4 | import numpy as np
# Linear Regression Class using Multi-dimensional Gradient Descent
class LinearRegressionMGD():
def __init__(self):
# degree: used to store number of dimensions of the coeffcients in m
self.degree=0
# m : similar to slope but has multiple variable... |
3f467371cd1c560c32192005b81406d5dd96d046 | stats-calculator/coding-exercise | /stats/welford.py | 1,436 | 4.09375 | 4 | """
An implementation of Welford's online algorithm.
See https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford%27s_online_algorithm
"""
import math
def update(count: int, mean: float, m2: float, new_value: float) -> tuple:
"""
For a new value and current tracking data, compute the new
... |
1bde48e7f4a98135a52da4e61d5eba017a4918a2 | cwrc/CWRC-Misc | /misc/scripts/csv2json.py | 563 | 3.921875 | 4 | #!/usr/bin/env python
# MRB -- Thu 05-Jun-2014
"""
Purpose:
Convert a CSV file to a JSON file
Usage:
python csv2json.py
"""
import csv
import json
# Change to the appropriate input CSV file
f = open( 'input_file.csv', 'rU' )
# Change each field name to the appropriate field name
reader = csv.DictReader( f, ... |
0529a60826b20eed2e192aa8a3d19e2a0c0513f4 | joeiddon/aqa_comsci_a_level | /2018 Pre-Release/Skeleton Programs/rmme.py | 733 | 3.671875 | 4 | def BinaryEncode(Message):
Bytes = []
Current = 128
Count = 0
for Character in Message:
print('considering Character \'' + Character + '\'')
print('Count is', Count)
print('Current is', Current)
print('Bytes is', Bytes)
if Current == 0.5:
Bytes.append(... |
e464c2796f08f3b43d90d76925efbadd4799f724 | stephkno/CS_21_Python | /disjoint_sets/src/disjointSet.py | 1,801 | 3.75 | 4 | #!/usr/bin/python3
#disjoint set
#create_set() creates new set with one node
#union()
#find()
import random
import sys
sys.setrecursionlimit(99999)
#class to represent subset node
class SetNode:
def __init__(self, value):
self.value = value+1
self.parent = self
self.rank = 1
#class to represent set of subse... |
344aecddbd2e490abc9543d7e9b1497005405495 | turtlegraphics/slu-transcript-tools | /transcript.py | 7,024 | 3.53125 | 4 | # transcript.py
#
# Class for parsing transcript info
#
import re
import logging
"""Class that stores transcript information, built from the source of
the banner transcript display page.
This allows for manual or automatic use."""
class Course:
def __init__(self,name,title,term,grade,hours,qp):
self.name... |
e8ef3eb48d858aa93f65c2a90e49b493a7b0bdbd | Lynceusthepotato/MRS_ORDER | /Old homework i forgot the date/reverse and total even number.py | 867 | 4.28125 | 4 | def reverse():
a = input("Write here : ")[::-1]
print(a)
def total_of_even_number():
valuesearch = int(input("Enter the max value : "))
total = 0
for numb in range(1, valuesearch+1): # +1 so it stop at the number the user input
if(numb % 2 == 0):
print("{0}".format(numb))
... |
cacfaf9838e55d435165cde2a47d7bb4c440e44a | sctu/sctu-ds-2019 | /1806101049马原涛/lab02/test-three.py | 313 | 3.609375 | 4 | # 3、编程实现回文数判断。
#
# 输入:abcdcba
# c
# 输出:True
str=input()
a='123'
for i in range(1,len(str)+1):
a+=str[-i]
if str==a:
print('Ture')
else:
print('False')
|
f96a20fad476c1190cc2266f1dc92100105a5e2e | guojia60180/algorithm | /算法题目/算法题目/剑指offer/题61扑克牌中的顺子.py | 1,040 | 3.734375 | 4 | #Author guo
#首先数组排序
#统计排序后数组相邻数字之间空缺总数
#空缺综述小于或者等于0的个数,数组连续
# -*- coding:utf-8 -*-
class Solution:
def IsContinuous(self, numbers):
# write code here
if numbers==None or len(numbers)<=0:
return False
dic={'A':1,'J':11,'Q':12,'K':13}
for i in range(len(numbers)):
... |
c94dfa49fb341906f3915db5ee07ed88e855d7e5 | kaifist/Rosalind_ex | /old_ex/k--mers_lexico_order.py | 872 | 3.75 | 4 | # Enumerating k-mers Lexicographically
##import itertools as it
##
##with open('rosalind_lexf.txt') as file:
## letras = file.readline().rstrip('\n').split()
## letras2 = ''.join(letras)
## print(letras2)
## n = int(file.readline())
##
## print(letras)
## print(letras2)
## lista_perm = it.product(letras2, repeat=n)
##... |
8d432fbc23e8f324d6ba0ff732267709b44572cc | cylinder-lee-cn/LeetCode | /LeetCode/350.py | 1,545 | 3.984375 | 4 | """
350. 两个数组的交集 II
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2,2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [4,9]
说明:
输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
我们可以不考虑输出结果的顺序。
进阶:
如果给定的数组已经排好序呢?你将如何优化你的算法?
如果 nums1 的大小比 nums2 小很多,哪种方法更优?
如果 nums2 的元素存储在磁盘上,磁盘内存是有限... |
e222228a976a288782d31f8b4fb33895692cdc54 | SoniaAmezcua/python_class | /class05.py | 1,643 | 4.09375 | 4 | # -*- coding: cp1252 -*-
import random
"""
numero = random.randint(1,10)
print ("El número es {}:".format(numero))
for num in range(1, numero + 1):
print("*" * num)
"""
#Break
"""
for numero in range(1,10):
if numero % 2 == 0:
print('Tenemos un número par: {}, no continuamos'.format(numero))
br... |
35b24a441b586f6356af676438d82258e7dc8871 | IbadMukrom/python-basic-best-practices | /tipe_data/dictionary.py | 439 | 3.828125 | 4 | # dictionary adalah tipe data yang anggotanya terdiri dari kuncy(key) dan nilai(value)
dct = {'name:':'bonjovi',
'age:':20,
'address:': 'america'
}
print(dct)
for i in dct.keys(): # menggunakan perulangan untuk mengakses key saja
print(i)
for j in dct.values(): # menggunakan perulangan untuk ... |
4ec949dcbff4aa50a475a20555b3dd244e32ecf9 | psangappa/mario | /app/save_princess/possible_path.py | 1,744 | 4.09375 | 4 | """ If there is no shortest path exist, then find the possible path to the princes """
from app.save_princess.const import PRINCESS, MARIO, OBSTACLE, UP, DOWN, RIGHT, LEFT
class PossiblePathFinder:
def __init__(self, n, grid):
self.possible_path = []
self.n = n
self.grid = grid
def fi... |
ca55ec20553473a7f69ec37c42eaeaa0087d2fbe | Zi-Shane/leetcode-python | /leetcode/0209_word_pattern.py | 1,916 | 3.609375 | 4 | class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split(" ")
if len(pattern) != len(words):
return False
char_word_map_a = {}
char_word_map_b = {}
for i in range(len(pattern)):
if pattern[i] not in char_word_map_a:... |
d134da4b63b73498bedd4432526bb6014ef61d4c | EXPEbrlucas/emojify_python_script | /emojify_python_script.py | 2,371 | 3.5 | 4 | import sys
'''
emojify_python_script
#Description
Obfuscate your python script by converting an input script to an output script that functions the same (hopefully) but encodes the code as emoji icons.
#Usage
python emojify_python_script.py input_script.py output_script.py
#Example
cat input_script.py
print('... |
63086b9becfce64c61f05024b75751c3866e80fa | redashu/summer19b1_python | /web.py | 728 | 3.5 | 4 | #!/usr/bin/python3
import requests
from bs4 import BeautifulSoup
#print(dir(requests))
# we are using get request to load website a browser
# loading url
web=requests.get('http://192.168.10.30/adhoc.html')
print(web) # http response code
# web have more things also
#print(dir(web))
#print(web.content)
# ... |
3183c1cbf3a3c2bdb83ef931c83f8ea61f16facf | wang-jiankun/Machine-Learning | /ml-py/Logistic/Gradient ascent.py | 2,792 | 3.609375 | 4 | """
机器学习实战--Logistic 回归--demo
date:2018-7-12
author: 王建坤
"""
import numpy as np
from matplotlib import pyplot as plt
# 加载数据集
def loadDataset(filename):
# 数据集
dataList = []
# 数据样本
labelsList = []
fr = open(filename)
for line in fr.readlines():
lineArr = line.strip().split()
# 添加... |
3e933bb44883742bea1c985ab515667050632b30 | AshelyXL/PycharmProjects | /venv/BasicKnowledge.py | 544 | 4.0625 | 4 | a = '''This symbol has more lines
one line
two line
three line'''
print(a)
# ====================
#格式化方法format
age = 20
name = 'Swaroop'
print('{0} was {1} years old.'.format(name,age),end=' ')
print('{0} is playing'.format(name))
print('{0:.3f}'.format(1.0/3)) #三位浮点数
print('{0:_^11}'.format('hello')) #总字符长为11并用下划线填... |
38f401ec5e963122e3f6a73c58aacc487cab1f8a | LarmIg/Algoritmos-Python | /CAPITULO 8/Exercicio J.py | 818 | 3.96875 | 4 | # Elaborar um programa que leia uma matriz A de duas dimensões com seis linhas e cinco colunas. Construir a matriz B de mesma dimensão, que deve ser formada do seguinte modo: para cada elemento par da matriz A deve ser somado 5 e de cada elemento ímpar da matriz A deve ser subtraído 4. Apresentar ao final as matrizes ... |
595f7e05421b5165c786fc1b7d14d4dc5333d345 | ganjingcatherine/LeetCode-1 | /Python/Subsets.py | 1,169 | 3.796875 | 4 | """
Given a set of distinct integers, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If S = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
"""
class Solution:
... |
37a7695fbfd905e211e2498376a1bfbc006d0a84 | Coutlaw/Programming-1 | /avGrades.py | 250 | 3.90625 | 4 | def avGrades():
numGrades = 30
gradeTotal = 0
for i in range(numGrades):
grade = eval(input("Enter grade" +str(i+1) +": "))
gradeTotal += grade
average = gradeTotal / numGrades
print("Your average is:", average)
|
236face02dd707539e3f5cfaa29294203df96b92 | ayanbasak13/C-Basic-Codes | /fib_prac.py | 149 | 3.640625 | 4 | fib=[]
for i in range(0,10) :
fib.append(0)
fib[0] = 0
fib[1] = 1
for i in range (2,10) :
fib[i] = fib[i-1] + fib[i-2]
print(fib) |
f0e3e373bcfdc8e4dac235b1a383dee054ff2774 | gauresh29/gitfirstpro | /pract7.py | 567 | 4.0625 | 4 | """
author:gauresh
date:27/10/2021
perpose :practical like serch engine
"""
def findword(lis,quer):
i=0
word=''
if any(quer in word for word in lis):
print(f'\{quer}\ is there inside the list!')
print(word)
i+=1
#print(lis.count(word))
else:
print('\'AskPython\' i... |
0004b320c2149f5a7b77170f6c4631f803107e4a | aaronkyriesenbach/euler | /p215/generatePossibleWalls.py | 1,130 | 4.0625 | 4 | # Consider the problem of building a wall out of 2×1 and 3×1 bricks (horizontal × vertical dimensions) such that, for extra strength, the gaps between horizontally-adjacent
# bricks never line up in consecutive layers, i.e. never form a "running crack".
# There are eight ways of forming a crack-free 9×3 wall, written W... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.