blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
26357e594456b9fd9d756971015f21f7d7ea9de9 | nickfrasco/C200 | /Assignment5/mystuff.py | 299 | 3.5 | 4 | #created as Add New Item Python Package called mystuff
#parameter non-negative integer x
#return factorial of x
def fact(x):
result = 1
for num in range(2, x+1, 1):
result *= num
return result
def pascal_number(row,column):
return fact(row)/(fact(column)*fact(row-column)) |
18776014173ce53fb8825317e64485ee919bbac8 | lschanne/DailyCodingProblems | /year_2019/month_05/2019_05_01__non_overlapping_intervals.py | 1,289 | 3.96875 | 4 | '''
May 1, 2019
Given a list of possibly overlapping intervals, return a new list of intervals
where all overlapping intervals have been merged.
The input list is not necessarily ordered in any way.
For example, given [(1, 3), (5, 8), (4, 10), (20, 25)], you should return
[(1, 3), (4, 10), (20, 25)].
'''
# So it's ... |
e475a1f8809d0f7ed0fe00d905c780a8db055063 | joaoFelix/learn-python | /challenges/SecretNumberGuessGame.py | 336 | 3.890625 | 4 | secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input("Guess: "))
guess_count += 1
if guess == secret_number:
print("You won!")
break
else: # while loops may have else blocks (it gets executed if no break is executed in the loop)
print("Sor... |
47a45bcd16a7fa32f957bd000f4c936153d75e56 | Asiadav/MyPythonCode | /Python Projects for Class/Finished/temperature calc.py | 161 | 3.984375 | 4 | for i in range(1,2):
initTemp = float(input("Temperature in farenheit:"))
x = initTemp - 32
initTemp = x / 1.8
print(initTemp,"Degrees Celsius")
|
31d387dc40899ae7005508ea7a9c9b55c1943c0f | zhankq/pythonlearn | /website/菜鸟教程/《基础》/17迭代器与生成器/demo.py | 63 | 3.796875 | 4 | lst = [1,2,3,4]
it = iter(lst)
for x in it:
print(x,",")
|
a167fe9589155c1ba39e2ee2c0e267543a62272a | Iansdfg/Leetcode2ndTime | /79. Word Search.py | 802 | 3.609375 | 4 | class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
for i in range(len(board)):
for j in range(len(board[0])):
if self.findNext(i,j, board, word):return True
return... |
8bf063b5146afe9da5d3c5819ce0ca7707171ed5 | wilsonfr4nco/cursopython | /Modulo_Basico/Formantando_valores_modificadores/aula17.py | 1,508 | 4.15625 | 4 | """
Formatando valores com modificadores - Aula5
:s - Texto (strings)
:d - Inteiros (int)
:f - Números de ponto flutuante (float)
:. (NÚMERO):f - Quantidade de casas decimais (float)
: (CARACTERE) (> ou < ou ^) (QUANTIDADE) (TIPO - s, d ou f)
> - Esquerda
< - Direita
^ - Centro
"""
num_1 = 10
num_2 = 3
divisao = num... |
624ea5222fea203c7c8bf96e093cd9ded398e3a7 | GabrielGodefroy/sudoku | /impl/python/sudoku/solver/algo_X_impl/algo_X_impl.py | 2,247 | 3.8125 | 4 | """
Exact cover problem solver implemented using Donald Knuth's algorithm X
- [Exact cover problem wikipedia page](https://en.wikipedia.org/wiki/Exact_cover)
- [Knuth's Algorithm X wikipedia page](https://en.wikipedia.org/wiki/Knuth%27s_Algorithm_X)
Exact cover problem description:
- Given a set X
- And given Y,... |
11d55caf452b863db5661fee1f4fec600075c173 | WonyJeong/algorithm-study | /wndnjs9878/function/bj-4673.py | 1,010 | 3.5625 | 4 | #4673
def noSelfNumber(num) :
origin = num
result = origin #생성자 자체를 더하고
while True :
result += num%10 #한 자리씩 더한다
num = int(num/10) #일의자리수부터 상위자리수로 올라가기 위함
if num == 0 : break #가장 상위자리수가 되었을 때 나눗셈의 결과는 0이 되고 그럼 더이상 더할 필요 없어지므로 빠져나온다
return result #생성자가 존재하는 수가 리턴됨
def num... |
8d87a2fcc68cba237b503055cb24f0a46c548ccc | zmyao88/datascience_hw2 | /src/reformat.py | 4,874 | 3.640625 | 4 | #!/usr/bin/env python
from optparse import OptionParser
import sys
import csv
import homework_02.src.common as common
# pdb.set_trace()
def main():
r"""
Reads a comma delimited file, reformats, prints to stdout.
The reformat actions are:
1) Converts header to lowercase
2) Converts spaces t... |
20188ed3eba12d46bbe22a3d58ccf7b32851586f | Jude-A/France-IOI | /Lvl-1/07-Conditions avancées, opérateurs booléens/06-Casernes de pompiers.py | 350 | 3.84375 | 4 | paireZones=int(input())
for loop in range(paireZones) :
xMinA=int(input())
xMaxA=int(input())
yMinA=int(input())
yMaxA=int(input())
xMinB=int(input())
xMaxB=int(input())
yMinB=int(input())
yMaxB=int(input())
if xMinB>=xMaxA or xMaxB<=xMinA or yMinB>=yMaxA or yMaxB<=yMinA :
print("NON")... |
f0b80d1b33f9ab4a6724c8c77af4e1c5c242ab8f | ktaletsk/daily-problem | /977/Python/solution.py | 1,817 | 3.609375 | 4 | import pytest
import math
from typing import List
import numpy as np
def find_first_nonnegative(ar, ibegin=None, iend=None):
if ibegin == None:
ibegin = 0
if iend == None:
iend = len(ar) - 1
if ibegin > iend:
return -1
# Find a middle
m = ibegin + (iend - ibegin + 1) // 2... |
72a2a41dbf63ff08ada0fa780c759bebe3eed68d | HarshitRatan/Python-QRcode-Generator-GUI | /QRcode-Generator-GUI.py | 2,910 | 4.125 | 4 | #Code By Harshit Ratan Shukla
#QR code stands for Quick Response Code. QR codes may look simple but they are capable of storing lots of data.
#Irrespective of how much data they contain when scanned QR code allows the user to access information instantly. That is why they are called Quick Response Code.
#These are bei... |
448e7c69673090ee3fb650c64c37126997e151d0 | Khrystynka/LeetCodeProblems | /35_search-insert-position.py | 817 | 3.625 | 4 | # Problem Title: Search Insert Position
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if nums == []:
return 0
n = len(nums)
l_id = 0
r_id = n-1
whi... |
05aeda42cc4f675f7d1c50c783000bf274deb86f | goushan33/PycharmProjects | /learn_notes/leetcode/linkLoop.py | 2,027 | 3.875 | 4 | '''
首先,关于单链表中的环,一般涉及到一下问题:
1.给一个单链表,判断其中是否有环的存在;
2.如果存在环,找出环的入口点;
3.如果存在环,求出环上节点的个数;
4.如果存在环,求出链表的长度;
5.如果存在环,求出环上距离任意一个节点最远的点(对面节点);
6.(扩展)如何判断两个无环链表是否相交;
7.(扩展)如果相交,求出第一个相交的节点
'''
class Node():
def __init__(self,val):
self.val=val
self.next=None
#1.给一个单链表,判断其中是否有环的存在;
def isLoopLink(head):... |
5fbce063bc3007d9a51ffa5c0b54056542bff71a | Haritha1115/luminardjango | /luminarprojects/collectin/evenodd.py | 379 | 4.03125 | 4 | # prg to enter list by user
# limit = int(input("enter the limit :"))
# lst = list()
# for i in range(0, limit):
# element = int(input("enter the no."))
# lst.append(element)
# print(lst)
even = list()
odd = list()
for i in range(0, 501):
if i % 2 == 0:
even.append(i)
else:
odd.append(i)... |
3b127175fa9ff11a340ab46c61c1ca976d7e6722 | ozmaws/Chapter-5 | /CH5P10.py | 1,174 | 3.890625 | 4 | import random
hedges = ("Hello. ", "How are you? ", "I would like to order a drink. ")
qualifiers = ("I feel uneasy. ", "Why do you do this? ", "I cannot continue like this ")
replacements = {"I":"you", "me":"you", "my":"your", "we":"you", "us":"you", "mine":"yours", "you":"I", "your":"my", "yours":"mine"}
def repl... |
a0a8a02f861a5c79fdbe491b98ede334f4376405 | Ifo0/Soft-uni | /Week3_Exercises.py | 4,120 | 3.5 | 4 | # Zadacha 1
# time_a = int(input())
# time_b = int(input())
# time_c = int(input())
#
# total_time = time_a + time_b + time_c
#
# if total_time < 60:
# print('0:' + f'{total_time}'.zfill(2))
# elif total_time >= 60 and total_time < 120:
# print('1:' + f'{total_time % 60}'.zfill(2))
# else:
# print('2:' + f'... |
b8adb3e902308c88dab8bc30f619a01df1696054 | wirabhakti/Simple-Algorithm | /insertionsort.py | 176 | 3.953125 | 4 | #!/usr/bin/env python3
def insertion_sort(arr):
selected_num = arr[0]
for i in range(len(arr)):
selected_num = arr[i+1]
for i in arr[:selected_num]:
|
96c23652f92c4ef9283f905f354c25e875bb7b03 | michelemarzollo/cil_sentimental_sourdough | /preprocess_tweets/vocab_keep_freq.py | 493 | 3.546875 | 4 | #!/usr/bin/env python3
import pickle
import sys
def main():
'''
Creates a dictionary to map words in the vocabulary to their frequency in the corpus.
'''
vocab = dict()
with open(sys.argv[1]+'.txt') as f:
for line in f:
c, w = line.strip().split(' ')
vocab[w.strip()]... |
fa6dee82216a99db205260cf30199693e23b87b3 | oicebot/4pic1wordsolver | /wordfinder_py2.py | 2,150 | 3.84375 | 4 | #!/usr/bin/python2
# -*- coding:utf-8 -*-
required = 'dictionary'
number = 3
print u'4Pic1Word作弊器 v1.1 by Oicebot @Guokr.com '
print ' '
while True:
print u'请输入题中所给字母,不区分大小写,退出请直接回车:',
required = str(raw_input()).lower()
if len(required) < 1:
print u'完毕,感谢使用。'
break
if not required.is... |
20e7898a7560c068352be033914b10bd845ea6a7 | NoahBlack012/ecosystem_v2 | /src/simulation/world/Food.py | 769 | 3.6875 | 4 | import random
class food:
def __init__(self, nutrition, amount, sickness_chance):
"""
Nutrition: Hunger value gained from food
Amount: Number of servings avalible
Sickness chance: % Chance of getting sickness - Sickness reduces health
"""
self.type = "food"
# ... |
a2f566b7694bbdd6ad3852661ff441c52b6bd444 | ancabilloni/ds_algo_problems | /isListPalindrome.py | 1,338 | 3.78125 | 4 | # Singly-linked lists are already defined with this interface:
# class ListNode(object):
# def __init__(self, x):
# self.value = x
# self.next = None
#
# def isListPalindrome(l):
# """ Time & Space: O(n)"""
# s = []
# tmp = l
# while tmp:
# s.append(tmp.value)
# tmp = tmp.next
... |
c1ec323b5e7ecfb52fb8b57d910a1ba8b32d90cd | RodrigoVillalba/Tp-estadistica | /main.py | 1,616 | 3.578125 | 4 | # Tp de estadistica
import random
import math
#1. Utilizando únicamente la función random de su lenguaje (la función que genera un número aleatorio uniforme entre 0 y 1),
def calcularAleatorio():
numAleatorio = random.random()
return numAleatorio
#implemente una función que genere un número distribuido Bernoul... |
3d37dc555a543dbdd32fe246df87500320975396 | hansangwoo1969/iot_python2019 | /01_Jump_to_python/3_control/2_while/7_141.py | 365 | 3.640625 | 4 | #coding: cp949
total = 0
for i in range(10):
# print(i, end = ' ')
print("%d"%i, end = ' ')
total = total + i
print("\t\t => total: %d"%total)
total = 0
for i in range(1,11):
print(i, end= ' ')
total += i
print("\t\t => total: ", total)
total = 0
for i in range(1,11, 2):
print(i, end= ' ')
... |
f086f9ae90c6d4593384b82b65654418c331b9a9 | Arnukk/DAA | /Hmw1/Q3_3.py | 1,170 | 3.8125 | 4 | __author__ = 'akarapetyan'
from numpy import loadtxt
# A simple function for reading the file and checking whether it is compatible with the input rules
def checkMe(function):
#Loading the input file
temp = loadtxt('test.in', dtype='str')
#Checking if the input parameters are right
if temp[0].isdigit(... |
9cdadbb6583fc9acb93b22dd6bbfda52f67db548 | HY36/python | /call.py | 167 | 3.546875 | 4 | class Student(object):
def __init__(self,name):
self.name=name
def __call__(self):
print('My name is %s' %self.name)
s=Student('Micheal')
s() |
4e31ef5eb032dd0883b0969abf2aae8e9c3948f9 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_2_neat/16_0_2_jermenkoo_gcjC.py | 335 | 3.703125 | 4 | def pancake(order):
flip = 0
good, bad = '+', '-'
index = len(order)
for i in range(len(order) - 1, -1, -1):
if order[i] == bad:
flip += 1
good, bad = bad, good
return flip
N = int(input())
for i in range(N):
print("Case #{}: {}".format(i + 1, panca... |
58099762edfabd339ccfe2b20b0012329d79a98d | Kimseogyeom/Python_basic | /Lotto.py | 1,079 | 3.59375 | 4 | import random
def input_Num(list):
for i in range(0,6):
if list[i] != 0:
continue
num = int(input("%d번째 자리의 번호를 입력해주세요(1~45):" %(i+1)))
if num < 1 or num > 45:
print("1번부터 45번까지만 입력해주세요")
return input_Num(list)
for j in list:
if j == n... |
205414c5a5c28d0d35df71b9449b26b9d420cc8d | gastbob40/fmsi | /miller.py | 1,234 | 3.703125 | 4 | import random
def miller_rabin_pass(a, s, d, n):
"""
check si n respect bien le miller_rabin test
"""
a_to_power = pow(a, d, n)
i = 0
if a_to_power == 1:
return True
# a^(d*2^i) = n-1 mod n
while i < s - 1:
if a_to_power == n - 1:
return True
a_to_... |
cdcd8424d8f9f8397549dbe8ea17485f760857b8 | deepaksharma36/Python-Assignements | /Sample/sample.py | 401 | 3.8125 | 4 | import turtle
def drawSquare(length):
turtle.forward(length)
turtle.left(90)
turtle.forward(length)
turtle.left(90)
turtle.forward(length)
turtle.left(90)
turtle.forward(length)
turtle.left(90)
def main():
length = int(input('Enter side length: '))
drawSquare(leng... |
51387225bd26ab04872b16ef0e683e7cfe0b3fe4 | basicskywards/data_structures_algorithms | /Binary_Search_Trees/Python/bst_check.py | 963 | 4.03125 | 4 |
import random
import sys
from binary_tree_base import Binary_Tree_Node
# naive time complexity O(n^2)
# time complexity O(n)
def is_binary_tree_bst(tree, low_range=float('-inf'), high_range=float('inf')):
if not tree:
return True
elif not low_range <= tree.data <= high_range:
return False
return (is_binary_tre... |
3720505e6111323799ceecd0fbbaf6fe25b35361 | lcx94/python_daily | /data_structure/2020-07/20200719/relative_sort_array.py | 1,012 | 4.34375 | 4 | # -*- coding:utf-8 _*-
'''
@author: lcx
@file: relative_sort_array.py
@time: 2020/7/20 9:50
@desc:
Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.
Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2.
Elements th... |
ae416eaba527e46a2d44cd198b0d819558c37d11 | Unbeaten123/Take-others-as-mine | /Print_Prime_number.py | 420 | 4 | 4 | # -*- coding: utf-8 -*-
#利用fliter函数输出1000范围内的所有质数
#Using the fliter function to print all the prime number within 1000
def Prime_num(n):
if n == 2 or n == 3:
return True
elif n == 1 or n == 4:
return False
for k in range(2, n/2):
if (n%k == 0):
return False
... |
74a3a96452b29dfbd9b7eefde5c78d4ac7b18893 | yogisen/python | /basedeA-Z_-datascience/legislator.py | 936 | 3.65625 | 4 | import csv
f = open("legislators.csv")
legislators = list(csv.reader(f))
gender = []
for item in legislators:
gender.append(item[3])
print(set(gender)) # {'', 'M', 'gender', 'F'}
party = []
for item in legislators:
party.append(item[6])
print(set(party)) # {'', 'Liberty', 'Unconditional Unionist', 'Liberal R... |
f81259cfbd65e766de3bf29218a7154d4e2fc7e0 | Daoi/SumOfIntervals | /sum_of_intervals.py | 393 | 3.609375 | 4 | def sum_of_intervals(intervals):
from collections import Counter
interval = []
length = 0
for i in range(len(intervals)):
for j in range(len(intervals[i])):
for x in range(intervals[i][j], intervals[i][j+1]):
interval.append(x)
break
numbers = Counter... |
74959a44d64e15c95440be1b5936a3987e44c120 | moshoulix/ZOJ | /1005.py | 1,148 | 3.625 | 4 | # 水壶倒水问题 输入多个 小水壶 大水壶 目标
# 输出方案
# a b 互质则一定可以达到目标
#
# 解决:如果a空就灌满,a倒入b,判断b是否成功,重复
def prt(List):
numbers = {
0: 'fill A',
1: 'fill B',
2: 'empty B',
3: 'pour A B',
4: 'success'
}
for num in List:
print(numbers.get(num))
try:
while 1:
x = input().... |
8341aa833690818f2c607df6c028ec5447a448c5 | ParulProgrammingHub/assignment-1-arvind89 | /Ques11.py | 186 | 3.578125 | 4 | #compound intrest")
a=input("enter the amount")
a=float(a)
b=input("enter the rate")
b=float(b)
c=input("enter the time in year")
p=a*((1+float(b/100))**c)
interest=p-a
print(interest)
|
9409adbc4f9abac94b4b02970cd46a783fc125ad | Sajanader/amman-python-401d2 | /data_structures_and_algorithms_python/challenges/array_reverse/array_reverse.py | 151 | 3.921875 | 4 |
arr=[1,2,3,4,5]
def reverse_array():
reversedArr=[]
for i in arr:
reversedArr.insert(0,i)
print(reversedArr)
reverse_array() |
91fbfba74756e1c5dff0bb88b37a0b01540d2600 | SarkisyanC/Matrices-Solver | /gauss-jordan_solver_ver_2.py | 4,832 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Gauss - Jordan Elimination Helper
Created on Thu Jan 7 15:36:44 2021
Notice: This program is in no way meant to be used to cheat.
Use this program only to check your answers
and improve your understanding of gauss - jordan elimination
especially for ungrad... |
3f2cbf3fc8788f0f0ba8cf7a69e3631ad9e5f24b | dinesh1987/python-samples | /OOPS/basic_oops.py | 790 | 4.25 | 4 | observe1="What's happening"
observe2="creating Monkey class"
class Monkey:
def __init__(self):
observe4="creating instance vars of that obj."
self.breed=None
self.color=None
observe3="creating a Monkey object"
dunston=Monkey()
observe5="dunston refers to that object"
observe6="accessing ins... |
daa52f386046f1e866925c75a933a59a5567fe77 | chimeng62/Algorithm---Python | /Recursion/1.py | 180 | 3.84375 | 4 | arr= ['ab','c','def','aadd']
def charCount(array):
#base case
if len(array) == 0: return 0
return charCount(array[1:len(array)]) + len(array[0])
print(charCount(arr)) |
fd1b01d9223c357b6f4e46634f9508d6e345af41 | Andrewah1/comp110-21f-workspace | /exercises/ex01/numeric_operators.py | 532 | 3.90625 | 4 | """numeric_operators."""
__author__ = "730389123"
Left_hand_side = int(input("enter value for Left-hand side: "))
Right_hand_side = int(input("enter value for Right_hand_side: "))
print(Left_hand_side, "**", Right_hand_side, "is", (Left_hand_side ** Right_hand_side))
print(Left_hand_side, "/", Right_hand_side, "is",... |
ee9c4e257493ea07e58501966e145f74d7a5f593 | cogitum/PL | /PL01.py | 3,371 | 3.859375 | 4 | class Node:
def __init__(self, v):
self.value = v
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def add_in_tail(self, item):
if self.head is None:
self.head = item
else:
self.tail.next = i... |
d8ac62e01839bd13cf7f4f63419fbeacb30a622c | getState/Programmers-Algorithm | /Level1/35.최대공약수와최소공배수/35.최대공약수와최소공배수.py | 243 | 3.609375 | 4 | def findGcd(a, b):
while b!=0:
temp = a%b
a = b
b = temp
return a
def solution(n, m):
answer = []
gcd = findGcd(n, m)
lcm = (n*m) / gcd
answer.append(gcd)
answer.append(lcm)
return answer |
c9c5c480dfed86467274f8351047efc463994ffb | invisible-college/scripts | /add_evg_edu.py | 310 | 3.890625 | 4 | import sys
# First argument is the file to open / read
filename = raw_input();
file = open (filename, "r");
lines = file.readlines()
# To process a list of email addresses
# and add comma separation
string = ""
for line in lines:
line = line.strip() + "@evergreen.edu;"
string += line
print(string) |
ede6f0911d376ff0de5dfa5664f9b9f6b61b80f4 | jizhi/jizhipy | /Array/ArrayAxis.py | 6,944 | 3.6875 | 4 |
def _ArrayAxis( array, axis1, axis2, act='move' ) :
'''
array:
Any dimension array (real, complex, masked)
axis1, axis2, act:
act='move' : old a[axis1] becomes new b[axis2]
a.shape=(2,3,4,5,6)
b = ArrayAxis(a, 3, 1, 'move')
b.shape=(2,5,3,4,6)
act='exchange' : exchange a[axis1] with a[axis2]
a.sha... |
92b81c8f48e45793887c919b2baf8f2622e02c31 | Madhav2108/Python- | /basic programs/4.py | 193 | 3.890625 | 4 | P=int(input("Enter the Percentage"))
if P<40:
print("you are failed")
elif P<50:
print("You are Third")
elif P<60:
print("You are Second")
else:
print("you are First")
|
e69a237ca602cabc1c095b0f80db80f692020245 | mattheuslima/Projetos-Curso_Python | /Aulas/Aula 18.py | 1,909 | 4.125 | 4 | ''' Listas compostas (listas dentro de listas)'''
from time import sleep
teste=list()
teste.append('Mattheus')
teste.append('26')
galera=list()
galera.append(teste[:])
teste[0] = 'Lima'
teste[1]= '24'
#Dessa linha pra cima, a lista teste está como 'Lima','24'. Mas se eu fizer um novo append na inteção de ter [['Mattheu... |
925f6e21ac7390037875248505ac20070f56bdda | nicoekkart/python | /Project Euler/2.py | 1,053 | 3.953125 | 4 | """
Even Fibonacci Numbers
----------------------
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four millio... |
f0315866e3206f61438c89f50b71613483376aec | emiairi/Curso-em-video | /PythonExercicios/ex083 Validando expressoes matematicas.py | 940 | 4.15625 | 4 | # Desafio 083 - Validando expressões matemáticas
'''Crie um programa onde o usuário digite uma expressão qualquer e use parênteses. Seu aplicativo deverá analisar se a
expressão passada está com os parênteses aberto e fechado na ordem correta.'''
expressão = str(input('Digite a expressão: '))
aberto = fechado = 0
for... |
889a2a4634d6d57154bdf25c44b8bd8d08734bbf | Leahxuliu/Data-Structure-And-Algorithm | /Python/coding/Find Pair With Given Sum.py | 1,087 | 4.15625 | 4 | '''
Given a list of positive integers nums and an int target, return indices of the two numbers such that they add up to a target - 30.
Conditions:
You will pick exactly 2 numbers.
You cannot pick the same element twice.
If you have muliple pairs, select the pair with the largest number.
Example 1:
Input: nums = [1,... |
801a8fa2f03b6496e268d8155d5bb3239472987e | MichaelHannalla/NeuralNetwork | /mnistneuralnet_michaelhaidy_onetime.py | 5,922 | 3.71875 | 4 | # CSE488 - Computational Intelligence
# Faculty of Engineering - Ain Shams University
# Neural Network Project - MNIST Dataset
# Haidy Sorial Samy, 16P8104 | Michael Samy Hannalla, 16P8202
# Building of a modular neural network and training it using gradient descent optimization
import numpy as np
import matplo... |
14404bc6b2ee43d3fbd83bb1397362e7f2c35ee9 | jschnab/machine-learning | /svm/svm.py | 4,508 | 3.765625 | 4 | #script based on coursera Andrew Ng's ML course exercice 7 on SVM
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.io #load Octave .mat file
import scipy.optimize #fmin_cg
from sklearn import svm
#load Octave matrix
data = scipy.io.loadmat("ex6data1.mat")
X = data['X']
Y = data['y']... |
f447de5dc479d6b3dee3baeaa86545a85a15b487 | FirelCrafter/Code_wars_solutions | /6_kyu/Which_are_in.py | 213 | 3.640625 | 4 | def in_array(array1, array2):
array2 = ' '.join(array2)
return sorted(set(a for a in array1 if a in array2))
print(in_array(["live", "arp", "strong"], ["lively", "alive", "harp", "sharp", "armstrong"]))
|
462aee2736b68befa7bc471bb326b5a7ef2d2c78 | thienlerva/PythonTutorial | /PythonTutorial/dictionaryAndSet.py | 1,956 | 4.125 | 4 | # Dictionary is unordered, duplicates not allowed
carDict = {
"branch": "Ford",
"model": "Mustang",
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(carDict)
print(carDict["branch"])
print(len(carDict))
print(type(carDict))
# get value
print(carDict.get("colors")) # same as carDict["colors"]
... |
1cec0239eb1210a7470760fb1afa6da73c6fb4f3 | Arsen339/Classes | /TheoryIncapsulation3.py | 931 | 4.0625 | 4 | # Наследование
class Pet:
legs = 4
has_tail = True
def __init__(self, name):
self.name = name
def inspect(self):
print(self.__class__.__name__, self.name) # сслыка на класс объекта и на имя класса
print("Всего ног: ", 4)
print("Хвост присутствует-", 'да' if self.has_t... |
ef0f5bab0fcf232d0df6f970d8fe40826afe223f | PatrykDagiel/Python_Dawson | /Chapter VIII/zwierzak_z_wlasciwoscia.py | 753 | 3.765625 | 4 | class Critter(object):
"""Wirtualny pupil"""
def __init__(self, name):
print('Urodzil sie nowy zwierzak')
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, new_name):
if new_name == "":
print('Pusty lancuch -... |
b0d7304f91c533872273b1f2c5026da4a70de6c2 | castellanprime/DiscardMulti | /servermodel.py | 579 | 3.71875 | 4 | """
Server model
"""
class ServerModel(object):
def __init__(self, players):
self.players = players
self.initial_player = None
self.current_player = None
def get_initial_player(self):
return self.initial_player
def set_initial_player(self, player):
self.initial_player = player
print("Initial player... |
cc9608daa96f6eb8d06b7f7094f5ef717bbb35fc | GOGOPOWERRANGERFYF/python | /class_example/class_students.py | 1,843 | 3.890625 | 4 | '''
object oriented progamming 面向对象编程,是一种程序设计思想
在python中,所有数据类型都可以视为对象,当然也可以自定义对象,自定义的数据类型就是面向
对象中的类(class)
class类的变量variable和函数function (blueprint蓝图)
object对象的属性attribute和方法method
'''
# int float string boolean这些数据类型并不能表示一个学生,因此自定义一个学生数据类型,也就类class
class Students: #类的名称开头字母大写,一般遵循驼峰命名,只是约定俗成的规定,并非强制性,驼峰命名比如:M... |
d69934dba541eafd93350371885c433634652cba | ElielLaynes/Curso_Python3_Mundo1_Fundamentos | /Mundo1_Fundamentos/Aula07_Operadores_Aritméticos/DESAFIOS/desafio012.py | 399 | 3.765625 | 4 | # Faça um algotitmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.
preco_produto = float(input('Qual o preço do produto? '))
desconto = preco_produto * 0.05
preco_desconto = preco_produto - desconto
print('O preço Atual do Produto é R${:.2f}'.format(preco_produto))
print('APLICANDO 5% de D... |
5debbd30dff157b7f27283b3a8cdab440226e27f | HangZhongZH/Sort-Algorithms | /插入排序.py | 281 | 3.90625 | 4 | def insertionSort(nums):
length = len(nums)
for i in range(length - 1):
idx = i
currentnum = nums[i + 1]
while currentnum < nums[idx] and idx >= 0:
nums[idx + 1], nums[idx] = nums[idx], nums[idx + 1]
idx -= 1
return nums
|
32f11795d595cde531aea58b5af35afb0f7dba02 | acboulet/advent2020_py | /d6/day6.py | 3,329 | 3.984375 | 4 |
from os import name
def process_1(file_name):
"""
Purpose:
Process .txt file to check each unique character in a given group of passengers.
Groups of passengers are seperated by empty lines.
Pre:
:param file_name: name of .txt file
Return:
List of unique characters whe... |
c82769e6f6680ea2df9bf6959d783abc8018656a | Priyankasharma181/listPythonQuestions | /list.py | 74 | 3.703125 | 4 | list = [2,3,4,5,6]
a=len(list)
i=0
while i<a:
print(list[i])
i+=1
|
1e62ac8abfb97af94e82667b62dc1f9b34b5c268 | andriisoldatenko/fan | /uva_answers/120-stacks-of-flapjacks/main.py | 1,720 | 3.53125 | 4 | import sys
# FILE = sys.stdin
# FILE = open('sample.in')
def fopen(filename, default=sys.stdin):
"""
This function helps you do not see errors during upload solutions
because you forget to switch back to sys.stdin and also you can easily
debug your code with ipdb or another python debuggers
"""
... |
590687005283bbd3c2eccf37773150e760005ac5 | hirwaraissa/PythonProject | /Compound interet2.py | 534 | 3.953125 | 4 | def final_amt(p, r, n, t):
"""
Apply the compound interest formula to p
to produce the final amount.
"""
a = p * (1 + r/100) ** (n*t)
return a # This is new, and makes the function fruitful.
# now that we have the function above, let us call it.
p=int(input("How much do you want t... |
6251178bdbed12c3252fc1127ceb09b17229a2f0 | bhavikjadav/Python_Crash_Course_Eric_Matthes_Chapter_3 | /3.1_ Names.py | 405 | 3.953125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # 3-1. Names: Store the names of a few of your friends in a list called names. Print each person’s name by accessing each element in the list, one at a time.
# In[24]:
names = ["mehul", "jay", "jignesh", "pruthvi", "dhruv"]
# In[25]:
print(names[0].title())
print(names[1]... |
f1c7ea352dbeda69a96ac54abbe9bf52e7633ba4 | piara108/my-exercism-solutions | /python/anagram/anagram.py | 293 | 3.890625 | 4 | # Anagram
def find_anagrams(word, candidates):
anagrams = []
for term in candidates:
word_lower, term_lower = word.lower(), term.lower()
if word_lower != term_lower and sorted(word_lower) == sorted(term_lower):
anagrams.append(term)
return anagrams
|
e8309e2a142ce5b43a5533716d3042cfb0b01fad | conormccauley1999/CompetitiveProgramming | /Kattis/fizzbuzz.py | 217 | 3.5625 | 4 | i = raw_input().split(" ")
X, Y, N = int(i[0]), int(i[1]), int(i[2])
for i in range(1, N+1):
if i % X == 0 and i % Y == 0: print "FizzBuzz"
elif i % X == 0: print "Fizz"
elif i % Y == 0: print "Buzz"
else: print i |
b5292b30edd2242c6e98f736149fd5499f07130a | daniel-reich/ubiquitous-fiesta | /Njeob2pNQYsCd69fN_2.py | 199 | 3.53125 | 4 |
def prevent_distractions(txt):
lst = [
'anime',
'meme',
'vine',
'roasts',
'Danny DeVito'
]
for i in lst:
if i in txt:
return "NO!"
return "Safe watching!"
|
b4108fe2f832d393cb3633b31790c9ecb814a113 | jomarmartinezjordas/py4e | /Course 2/week3.py | 1,102 | 4.3125 | 4 | # Week 3
'''
Files
handle = open('filename', 'mode'); mode can be w or r [read or write]
\n - > new line
str.read() - reads the whole file (newlines and all into a single string)
str.startswith() -
--- print function adds a newline automatically at the end of a line
str.rstrip() - used to remove whitespace from print... |
e00113b5ab6665b0baaf79f61127c76d49f2813b | AlliBusa/DIY-Search | /datasearcher.py | 816 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import code
from bs4 import BeautifulSoup as Soup
data = pd.read_csv("/home/allison/dream5/DataBase.csv", encoding="utf-8")
df = pd.DataFrame(data)
def join_materials(*materials):
"""Joins the keywords to make one search term"""... |
e6d974f634d93bae6d128ce62a02f1af3fa6987a | Hemanthtm2/codes | /findlower.py | 234 | 3.984375 | 4 | #!/usr/bin/python
import string
def findlower(str,ch):
index=0
for ch in str:
if str[index]==ch:
if ch==string.lowercase:
return ch
index=index+1
return -1
print findlower("Hemanth",'e')
|
91bb751ba6876bc18aae8f55d323a9d7b4e09644 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2129/60776/294547.py | 219 | 3.640625 | 4 | a=int(input())
result=0
while(True):
if(a==1):
break
else:
if(a%2==1):
a=a-1
result=result+1
else:
a=int(a/2)
result=result+1
print(result) |
7afad263c15e077dc241504dce257388f78a84ca | anshumanairy/Hacker-Rank | /All Programs/Collections counter.py | 434 | 3.515625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
from collections import Counter
def func():
X=int(input(""))
c=input("")
list1=[""]*X
list1=list(map(int,c.split(' ')))
list1.sort()
N=int(input(""))
s=0
for i in range(0,N):
d=input("")
a,b=map(int,d.split(' '))
r... |
6eb64b2064fcc1b83dc18ce8f644dbabfdda182f | kevin11h/Interview-Practice | /random_walk_in_the_park.py | 1,139 | 3.65625 | 4 | import random
LARGE_NUMBER = 40
def true_half_of_the_time():
boolean_as_bit = random.randint(0, 1)
return boolean_as_bit
LENGTH_OF_THE_ROAD = 3
road_position = 0
def true_two_thirds_of_the_time():
# 1 % 3 = 4 % 3 = 1 <---Position 1
# 2 % 3 = 8 % 3 = 2 <---Position 2
# 3 % 3 = 12 % 3 = 0 <-... |
9dfa607618c8047e21c6c91476155c325c8a6904 | Dracoptera/100daysPython | /day3.py | 1,498 | 4.03125 | 4 | print('''
*******************************************************************************
) \ / (
/|\ )\_/( /|\
* / | \ (/\|/\) / | \ *
|`.___________/__|__o____\`|'/___o__|__\__________.'|
| '^` \|/ '^` ... |
5197991ddaeff4654afb0cb72f52d4d34af6461a | mashikro/code-challenges | /cycle_in_ll.py | 2,226 | 4.0625 | 4 | # Prompt:
# You have a singly-linked list ↴ and want to check if it contains a cycle.
# A singly-linked list is built with nodes, where each node has:
# node.next—the next node in the list.
# node.value—the data held in the node. For example, if our linked list stores people
# in line at the movies, node.v... |
ddca6bc1a15b5a27c81dbf66d5b53a12ecbe1191 | Govindeepu/Simple-Banking-System | /SimpleBankingSystem.py | 8,119 | 3.5625 | 4 | import random
import _sqlite3
conn = _sqlite3.connect('card.s3db')
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS card")
create_table = 'create table if not exists card (id INTEGER, number TEXT, pin TEXT, balance INTEGER DEFAULT 0);'
insert_data1 = "insert into card(number, pin) values (?, ?);"
insert_id ... |
6983bb4cd9bb2c1573785a4e04d6c246a886abf9 | leovasone/curso_python | /Work001/file015_loop_for.py | 1,684 | 4.03125 | 4 | """
Loop e For
"""
nome = "Madagascar é uma ilha"
lista = [3, 4, 5, 6]
numeros = range(1, 10) #é preciso transformar em lista
#exemplo1 para for (iterando em uma string)
for letra in nome:
print(letra)
print(' ')
#exemplo2 para for (iterando sobre uma lista)
for numero in lista:
print(numero)
print('---... |
92659ce591b7f05f92e96e6bf9f2c85514648cf8 | stanislavkozlovski/data_structures_feb_2016 | /SoftUni/Tree Traversal Algorithms - BFS and DFS/homework/find_the_root.py | 1,252 | 4.125 | 4 | """
You have a connected directed graph with N nodes and M edges. You are given the directed edges from one node to another.
The nodes are numbered from 0 to N-1 inclusive. Check whether the graph is a tree and find its root.
Input:
Read the input data from the console.
The first line holds the number of nodes N.
The ... |
d4117df67afb591db552a4f78d35daf1703e5d99 | LyCq/example | /demo1.py | 216 | 3.640625 | 4 | A0 = dict(zip(('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, 5)))
A1 = range(10)
A2 = [i for i in A1 if i in A0.items()]
A3 = [A0[s] for s in A0]
print("A0: ", A0)
print("A1: ", A1)
print("A2: ", A2)
print("A3: ", A3)
|
d96bcf03829ad2736301e957b2ff96f582ff3ba6 | TooCynical/TNN | /PAB/Perzeptron.py | 9,567 | 3.546875 | 4 | # Lucas S. lfh.slot@gmail.com
# Julian W. jjwarg@gmail.com
#
# University of Bonn
# November 2017
#
# Perzepetron.py
# Implementation of a perzeptron with hidden layers and learning.
import numpy as np
import re
import random
import Util
N_MAX = 1001
M_MAX = 30
T_MAX = 1001
class PerzLayer:
def __ini... |
20866a4c91c7b1df070be0c902588cc7039d7c91 | draconswan/Python-Character-Arena | /src/classes/Character.py | 2,926 | 3.765625 | 4 | """
Created on Apr 11, 2018
@author: Daniel Swan & Erin Swan
@email: ds235410@my.stchas.edu & es209931@my.stchas.edu
"""
from random import randint
# This class contains all of the information needed to build and use both players and opponents
class Character:
# Characters have:
# A name
... |
263957be6fd4bb64c0e92d2b91f82d948cdfb692 | william-eyre/Python | /Python/Day3/Day3/Tasks/Tuple.py | 481 | 4.5 | 4 | my_tuples = (1, 2, 3, 4, 5)
print(my_tuples)
# a for loop can iterate over the elements in a tuple
names = ('Holly', 'Warren', 'Ashley')
for n in names:
print(n)
# tuples support indexing
names = ('Holly', 'Warren', 'Ashley')
for i in range(len(names)):
print(names[i])
# create a tuple with just one element... |
20635bab95469bb003cda90a65c03d864ab14416 | prateekmewada/Create-Dynamic-SQL-View-in-Python | /src/PrateekFunctions.py | 8,831 | 3.546875 | 4 | '''Importing all the python standard libraries here.'''
import subprocess
import sys
import os
import csv
def fn_InstallLibraries(libraries):
'''This function checks whether any external python libraries are installed.
If the library is not installed already, it will install it via pip install'''
... |
fc3d5a7455e2fc1777c0a40bad586b8f0ea9baf8 | jdonszelmann/minecraft-in-python | /main/util.py | 1,613 | 3.953125 | 4 | def cube_vertices(x, y, z, n, faces):
"""Return the vertices of the cube at position x, y, z with size 2*n."""
data = '{0:06b}'.format(int(faces))
a = []
if data[2] == "1":
a += [ x - n, y + n, z - n, x - n, y + n, z + n, x + n, y + n, z + n, x + n, y + n, z - n] #top
if data[3] == "1":
a += [ x - n, y - n, ... |
c31d032087f40cee9f847feaf8672d239a278238 | Vaild/python-learn | /homework/20200707/54_以逗号分隔在进行格式转换.py | 258 | 3.9375 | 4 | #!/usr/bin/python3
# coding = UTF-8
string = '2.72, 5, 7, 3.14'
list1 = string.split(sep=', ')
print(list1)
for i in range(len(list1)):
if list1[i].isnumeric():
list1[i] = int(list1[i])
else:
list1[i] = float(list1[i])
print(list1)
|
147f5ae99cf05f433ab35ca2a8e578154eb0fe5a | jgrimald/charSheetGenerator | /sheetCreate.py | 9,324 | 4 | 4 | #Character Sheet Generator
#
#Will create a 3.5 Dungeons and Dragons Player Character
import random
# Returns a random element from the list of fantasy names in the text file on the list aList, or series[]
# This is how you get your first name
def getFirstName(aList):
return (aList[random.randint(0,len(aList))]... |
f6591df920e96745818c38d5446b008f0bd762c8 | EmilyOng/cp2019 | /perse_coding/round1_2019/q6_lemonade_stand.py | 155 | 3.953125 | 4 | a=int(input())
b=int(input())
if a>=20 and b>=3:
print("A")
elif a<20 and b>=3:
print("B")
elif a>=20 and b<3:
print("C")
else:
print("D")
|
6fcfafea97b719ad654eb10d10c575981bf6e102 | Illugi317/gagnaskipan | /PA_4/MCK.py | 507 | 3.5625 | 4 | class MyComparableKey:
def __init__(self,int_val, string_val):
self.int_val = int_val
self.string_val = string_val
def __lt__(self,other):
if self.int_val < other.int_val:
return True
elif self.int_val > other.int_val:
return False
elif self.... |
50e63e0ef1db6bf4ae4e5406b74e4c33e19ecaba | sudikshyakoju/sudikshya | /pythonlab/labwork.py | 273 | 3.921875 | 4 | '''WAP n students take k apples and distribute them to each evenly'''
students=int(input('enter number of students:'))
apples=int(input('enter number of apples:'))
d=(apples//students)
r=(apples%students)
print(f"each students {d}")
print(f"the remaining apples are {r}")
|
efab02a71633660bb62f137cadb9587444e14405 | dineshkumarkummara/my-basic-programs-in-java-and-python | /folders/python/instagram/64lambda.py | 288 | 4.03125 | 4 | #Lambdas (or inline functions) are very handy if the function body is short and simple.
#You don't need to create a full function using the "def" keyword.
#Use "lambda" instead, followed by the argument and the function body.
sqr=lambda x:x**2
for i in range(1,4):
print(sqr(i))
|
5144c339d1c04246ee84b37fcdef2257e9034a11 | minh-quang98/nguyenminhquang-fundamental-c4e20 | /Session02/Homework/turtle_1.py | 334 | 3.8125 | 4 | from turtle import *
shape("turtle")
color("blue")
speed(-1)
left(60)
for i in range(2):
forward(100)
left(60)
forward(100)
left(120)
forward(100)
left(60)
forward(100)
forward(100)
right(60)
forward(100)
right(120)
forward(100)
right(60)
forward(100)
left(9... |
1b05dfed403aa6eea8fba1879f9349e9d8f02a94 | byeongal/KMUCP | /week09/code05.py | 226 | 3.59375 | 4 | def average(number_list):
total = 0
for each in number_list:
total = total + each
return total / len(number_list)
number_list = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print("평균 :", average(number_list)) |
7e0b712a61c83d28d4bf6a71799efcec099c1745 | ancestor-mithril/UAIC_FII_RN_HW_1 | /functions.py | 4,128 | 4.125 | 4 | from typing import List
def split_equation(string: str) -> List[str]:
"""
:param string: an equation
:return: a list containing only integers and their signs, or empty string
"""
import re
max_split = 0
string = string.replace(" ", "")
delimiters = "x", "y", "z", "="
regex_pattern ... |
0941ae9dd2d5d18680f00e8d8d21b44b7b4f27ad | takushi-m/atcoder-work | /contests/abc116/b.py | 305 | 3.640625 | 4 | # -*- coding: utf-8 -*-
s = int(input())
d = {s:1}
before = s
i = 1
def f(n):
if n%2==0:
return n//2
else:
return 3*n+1
while True:
i += 1
ai = f(before)
if ai in d:
res = i
break
else:
d[ai] = i
before = ai
# print(d)
print(res)
|
a996f38947b6b213b362e7c836f681729e2be70a | jmarkIT/trakt_sync_sync | /database.py | 3,344 | 3.734375 | 4 | import sqlite3
from sqlite3 import Error
sqlite_file = "trakt_shows.db"
table_name = "shows"
p_key_column = "p_key"
stub_column = "show_stub"
show_column = "show_name"
season_column = "season"
episode_number_column = "episode_number"
episode_title_column = "episode_title"
watched_status_column = "watched_status"
hidd... |
fe47a44ff5e6472fe5fb0c7aa64a7362242d0525 | Tom-TBT/git_btm2017 | /solution/btm_bank.py | 867 | 3.84375 | 4 | import functionalities as func
options = ["Say hi","Add client","Add transaction","Look at money"]
def show_options():
index = 0
for option in options:
print(index,option)
index += 1
def reception():
print("Welcome to the BTM bank, what can we do for you today ?")
show_options()
... |
8bbf05d26b17e5e697d1a141599e30233b49ef6e | jaekyuoh/ProjectEuler_JQ | /Codility/PermCheck.py | 360 | 3.53125 | 4 | def solution(A):
# write your code in Python 2.7
max_element = max(A)
permutation_list = range(1,max_element+1)
A.sort()
if len(A) != len(permutation_list):
return 0
for i in range(0,len(A)):
if permutation_list[i] != A[i]:
return 0
return 1
if __name__ == '__mai... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.