blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
feeb147c1a3c1a59a25a618b7d20e17db12a9c1f | ericgtkb/shortest-path | /python/processgraph.py | 2,734 | 3.5 | 4 | import sys
import random
import argparse
def get_pair(num_vertices):
seen = set()
while True:
pair = tuple(random.choices(range(1, 1 + num_vertices), k=2))
if pair not in seen:
seen.add(tuple)
yield pair
def process(args):
try:
with open(args.graph, "r") a... |
1b1d56d60b3fa329b1c92d449996ba7d952da912 | jtanadi/drawbotSketches | /_lib/Bezier_LinearInterpolation.py | 1,356 | 3.734375 | 4 | """
Bezier object
Inputs are 4 points (2-on curves & 2 off-curves) expressed as (x, y) tuples
Bezier().findPoints()
Requires Bezier object to be instantiated (eg. bezier1 = Bezier(p1, p2, p3, p4))
Input is k; output is a list of points expressed as (x, y) tuples. The last pair is the point on curve.
Points along t ar... |
1e19f65fee9f41823823acf257c3bf86daf522d8 | battyone/Practical-Computational-Thinking-with-Python | /ch2_party.py | 261 | 3.75 | 4 | k = int(input("How many children are coming to the party? "))
T = 12 * k
if T == 200:
print("You are right on budget, at " + str(T))
elif T <= 200:
print("You are under budget, at " + str(T))
else:
print("You are over budget, at " + str(T))
|
b57f91af59f27f52b257769d2e0a296142d3f69c | juliamoraiss/python-CursoEmVideo | /Exercícios/ex028.py | 522 | 3.8125 | 4 | from random import randint
from time import sleep
print('-=-'*18)
print('Vou pensar em um número de 1 a 5. Tente adivinhar...')
print('-=-'*18)
n1 = int(input('Em qual número eu pensei? '))
print('PROCESSANDO...')
sleep(2)
n2 = (randint(0, 5))
if (n1 > 5):
print('O número deve ser entre 0 e 5')
else:
if (n1 == ... |
e00fcec0843dfbad9f126c2a6a4222c401e1d693 | JunhoKimLee/TCAT | /code/regression.py | 3,485 | 3.734375 | 4 | # The code used to run linear and logistic regressions on the data to model key relationships
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
from matplotlib import pyplot as plt
data = pd... |
ecd1085d8d92916b1b422b1b18c1b23d9f72bbfd | derickdeiro/Python_Basic_to_Advanced | /02-INTERMEDIARY/aula_16/exercicio48.py | 949 | 3.859375 | 4 | def saudacao():
nome = input('Como se chama? ')
print(f'Olá, {nome}.')
saudacao()
def soma():
n1 = int(input('Digite um número: '))
n2 = int(input('Digite um número: '))
n3 = int(input('Digite um número: '))
resultado = n1 + n2 + n3
print(f'A soma desses números é {resultado}.')
soma()
pri... |
e32f31b8952faeb79de7d98854a3d85c1824f020 | pingyourid/learnpython | /practice/9/demo.py | 606 | 3.953125 | 4 | from random import randint, choice
# result = randint(1, 6)
# print(result)
# books = ['tomas', 'sea', 'sun', 'fish', 'milk']
# random_book = choice(books)
# print(random_book)
class Die:
"""docstring for Die"""
def __init__(self, sides=6):
self.sides = sides
"""投骰子"""
def roll_die(self):
... |
df4cff76368db79d68d20d540c8b968b07c48288 | KleczkoPawel/Python | /lista3/zadanie2.py | 127 | 3.765625 | 4 | a=int(input())
if (a%2==0):
print('podana liczba jest parzysta')
elif (a%2!=0):
print('podana liczba jest nieparzysta') |
521e4d84f5a536d307f2cc9679d2de57e6b4bf53 | vijparmar/self_taught | /chapter_challenges/Chapter_6_10.py | 340 | 3.640625 | 4 | '''
Author: Vijay Parmar
Date: 2/25/19
Description: Slice the string "It was a bright cold day in April,
and the clocks were striking thirteen." to only include
the characters before the comma.
'''
str = "It was a bright cold day in April, and the clocks were striking thirteen."
str=str[:str... |
aaac1314f02fcf9e1106f5713eee89969cb6bcfa | achmand/ari5123_assignment | /src/lucrum/algo/finstats.py | 1,193 | 3.625 | 4 | """Functions used to get financial stats and other function related with finance."""
# Author: Dylan Vassallo <dylan.vassallo.18@um.edu.mt>
###### importing dependencies #############################################
import numpy as np
from scipy.stats import skew
from scipy.stats import kurtosis
###### financial fu... |
8400e8f353acfc72ecb7f4124ad23dea469bd017 | mlyangyue/leetcode | /array/max_subarray.py | 668 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Andy'
"""
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
动态规划 max(arr[n-1]+arr[n],arr[n... |
6af7e3b197e16d2fe78420adbb3bb433c815c78f | ContangoRango/Machine_Learning_AI_Blockchain | /DataCamp_Foundations_of_Predictive_Analytics_in_Python(Part 1)/4.3.Discretizing_all_variables.py | 1,790 | 3.515625 | 4 | '''Instead of discretizing the continuous variables one by one, it is easier to discretize them automatically.
To get a list of all the columns in Python, you can use
variables = basetable.columns
Only variables that are continuous should be discretized.
You can verify whether variables should be discretized by ch... |
4327d37605c33584113d668ae05db596f8426b65 | zhengchaoxuan/Lesson-Code | /Python/Python基础/day 13/验证类在另一个类中调用方法.py | 856 | 4.21875 | 4 | """
lesson 1 : 演示了100个线程向同一个银行账户转账(转入1元钱)的场景
Author : 郑超轩
Date : 2020.02.28
"""
class Account(object,):
def __init__(self):
self._balance = 0
def deposit(self,money):
"""计算存款的余额"""
new_balance = self._balance + money
#受理的时间0.1s
self._balance = new_balance
... |
f77e2d1b95eea9c9621c94c031ec7a271d0a61bb | colephalen/SP_2019_210A_classroom | /students/AndrewMiotke/session04/trigrams.py | 2,122 | 4.21875 | 4 | #!/usr/bin/env python3
import random
"""
Solution to trigram problem
"""
def read_file(filename):
"""
returns a list of words in the file
"""
words = [] # creates empty list
with open(filename) as text:
for line in text:
words.extend(line.split())
return words
def build_... |
ce1c7b95b85cbff2d2e39a1171dd96cee8340549 | jamarflowers/dazn-interview | /2.PYTHON/list.py | 451 | 3.875 | 4 | """
List is a collection which is ordered and changeable. Allows duplicate members.
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Set is a collection which is unordered and unindexed. No duplicate members.
Dictionary is a collection which is unordered, changeable and indexed. ... |
2aaf9c3f2c56864077bbe5802fd9320de16ee05e | shreeyamaharjan/Assignment | /Data Types/QN12.py | 185 | 4.15625 | 4 | string = (input("Enter any string : "))
print("The entered string is : ", string)
print("The string in upper case : ",string.upper())
print("The string in lower case : ",string.lower()) |
58b40117215e5496d31e6238cff5f80785b6e736 | SOURADEEP-DONNY/PYTHON-3-PROGRAMMING | /Python Classes and Inheritance/week 2/first.py | 739 | 3.875 | 4 | current_year=2020
class age_calculation:
def __init__(self,name,birth_year):
self.name=name
self.birth_year=birth_year
def getAge(self):
return current_year-self.birth_year
def __str__(self):
return '{} age {}'.format(self.name,self.getAge())
class Student(age_... |
f5e3e9657ca19719ab3a410b7882cb2f9e1f36ae | I-will-miss-you/CodePython | /Coursera/Introdução à Ciencia da Computação com Python Parte 1/Semana 04/Exercicios/digitos_adjacentes.py | 284 | 3.8125 | 4 | num = int(input("Digite um número inteiro: "))
igual = False
anterior = num % 10
num = num // 10
while num > 0 and not igual:
novo = num % 10
if(anterior == novo):
igual = True
else:
anterior = novo
num = num //10
print("sim" if igual else "não")
|
88e1b711494d503428c491e520509d85b74a8dac | firdausmehta/Python-Financial-and-Election-Records | /PyBank/main.py | 1,946 | 3.765625 | 4 | import os
import csv
# Variables
months = []
p = []
average_net_change = 0
total_months = 0
net_change = []
# Load csv file
csvpath = os.path.join('Resources', 'budget_data.csv')
with open(csvpath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
reader = csv.reader(csvfile)
next(re... |
112c7714846ab53931f47a376d6fb6af8dcefd3a | BruceHi/leetcode | /DFS/solveSudoku.py | 4,250 | 3.734375 | 4 | # 解数独(只需一个解即可)
from typing import List
import string
from Array.isValidSudoku import isValidSudoku
class Solution:
# def solveSudoku(self, board: List[List[str]]) -> None:
# self.solve(board)
#
# def solve(self, board):
#
# for i in range(9):
# for j in range(9):
# ... |
7959665756951a37e41d3c31b814d1808e7d1595 | rafnolly/Current-date-and-time | /Current date and time.py | 102 | 3.59375 | 4 | import datetime
now = datetime.datetime.now()
print()
print("The current date and time is",now)
|
69bbdbec97ad33c4ce6818cb1742179ebde41b00 | khoIT/10xclub-hw | /inclass-activities.py | 1,944 | 4.375 | 4 |
''' SET A
1. Unique items
Write a function that takes in an array. It should return a new array
containing only the elements that were unique in the original array.
For example:
ary = [1, 5, 5, 7, 16, 8, 1, 8]
unique = unique_items(ary)
unique # => [7, 16]
'''
from sets import Set
def unique_items(arr):
co... |
10061933ae91d4620b5edbf3da6ab3512834689b | jeffvswanson/DataStructuresAndAlgorithms | /Stanford/06_Selection/Deterministic/deterministic_selection_algorithm_example.py | 4,307 | 4.0625 | 4 | # deterministic_selection_algorithm_example.py
"""
An example of using the deterministic "median of medians" method to
conduct a selection in linear, O(n), runtime.
"""
from random import randint
def main():
target_list = [7, 2, 17, 12, 13, 8, 20, 4, 6, 3, 19, 1, 9, 5, 16, 10, 15,
18, 14, 11]
... |
93d58706f9145dfc0c25beb815e6c16ceef076ca | idinabs/python | /python-fundamental/007.latihan/main.py | 301 | 3.859375 | 4 | print("\nMencari rumus dari kelvin\n")
f = int(input("masukan suhu anda : "))
c = ((5 / 9) * f) - 32
k = (c + 273)
print("suhu anda adalah", k)
print("\nMencari rumus fahrenheit\n")
k1 = int(input("masukan suhu anda : "))
c1 = k1 - 273
f1 = ((9 / 5) * c1) + 32
print("suhu anda adalah", f1) |
7304f6581c998a5fad4b1a95d0e1aa84d4277a8d | alexshenyuefei/python- | /python/format字符串格式化.py | 1,106 | 3.953125 | 4 | # 通过{}和%来代替传统%
# 1、使用位置参数
name = ['LiSA', 30]
strings = 'my name is {},age{}.'.format('LiSA', 30)
print(strings)
strings = 'my name is {0},age{1},hello,{0}.'.format('LiSA', 30)
print(strings)
strings = 'my name is {},age{}.'.format(*name)
print(strings)
# 2使用关键字参数,关键字参数值要对得上,可用字典当关键字参数传入值,字典前加**即可
hashes=dict(name='L... |
387d1be03e42e99191161660ab17565e4ade50c5 | Nike0601/Codekata-Set2-Python | /prog17.py | 269 | 3.953125 | 4 | print("Enter number: ")
num=int(input())
list=[]
sum=0
n=len(str(num))
for i in str(num):
list.append(int(i)**n)
for i in list:
sum+=i
print(sum)
if sum==num:
print("Number is an armstrong number")
else:
print("Number is not an armstrong number")
|
edcd6550219e518bde8a38de55df91f0a4ccbc3d | EHAT32/Newton | /main.py | 2,038 | 3.59375 | 4 | import numpy as np
import math
#The first part of the lab
def first_eq(x):
f = x * np.log(x + 1) - 0.3
return f
def first_eq_deriv(x):
d = np.log(x + 1) + (x / (x + 1))
return d
#locator of the roots
def locate_root(x_l, x_r, dx_l, dx_r):
while first_eq(x_l) * first_eq(x_r) > 0:
x_l += ... |
f24ef478d9c93c10993dcba3681882693b8b0ff9 | ruxiz2020/algorithms_practice | /twosum_double_pointer.py | 264 | 3.75 | 4 | def twoSum(nums, target):
l = len(nums)
for i in range(0, len(nums) - 1):
for j in range(i + 1, l):
if nums[i] + nums[j] == target:
return[i, j]
arr = [3, 8, 6, 2, 5, 9]
print(twoSum(arr, 7))
print(twoSum(arr, 19))
|
8928f4e19fad21943c24ebfeea4610228b7922b9 | AleksLyubenov/1-D-Heat-Equation | /main.py | 1,926 | 3.6875 | 4 | if __name__ == '__main__':
import numpy as np
from fem import fem1d
def INSTRUCTIONS():
'''
INSTRUCTIONS:
call fem1d(a, b, n, bound, c1, c2, toll, max_it, plot_me)
a ==> LHS of interval
b ==> RHS of interval
c1 ==> val... |
d229bf379e9866538829c80d1660981cabf3186c | roshnideyic365/Two_dice_stimulator | /dice_stimulator.py | 1,885 | 4 | 4 | def display(n):
if(n==1):
print(" ----------")
print("| |")
print("| O |")
print("| |")
print(" ----------")
if(n==2):
print(" ----------")
print("| |")
print("| O O |")
print("| |")
... |
7543b02c1a9b9e391b163837313912eed087138e | SamuraiT/RSA_Algorithm | /RSA.py | 6,335 | 3.859375 | 4 | #RSA algorithm
"""
This module provides functions
which decode ciphers and encode messages
@author Tatsuro YASUKAWA
"""
from random import randint
from math import sqrt
########################## encoding ##############################
def generate_public_key(limit = 30):
"""
this function generates a public key ... |
7673c61325ec6b9b20d9cf436a82919bd6103d31 | shobhit-nigam/yagami | /day2/flow_control/2.py | 248 | 3.859375 | 4 | vala = 100
if vala>=150:
print("guten tag")
# some code
elif vala>100:
print("salaam")
elif vala>=50:
print("namaste")
elif vala == 100:
print("sat sri akaal")
else:
print("good morning")
print("outside the if-else block")
|
9e8355760a6ef2b16056b765ee876f17aa6604fc | kfrancischen/leetcode | /python/78_subsets/subsets.py | 732 | 3.921875 | 4 | import copy
class Solution(object):
def backTracking(self, nums, subset, solution, start):
subset.append(copy.deepcopy(solution))
if start == len(nums):
return
for i in range(start, len(nums)):
solution.append(nums[i])
self.backTracking(nums, subset, solu... |
61cd9231f2ae5b9d0a933cc0102273b5adb317b6 | DeborahPerez/Rosalind_Bioinformatics_DAP | /ConsensusAndProfile.py | 808 | 3.640625 | 4 |
# coding: utf-8
# In[22]:
COLLECTION = ">Rosalind_1ATCCAGCT>Rosalind_2GGGCAACT>Rosalind_3ATGGATCT>Rosalind_4AAGCAACC>Rosalind_5TTGGAACT>Rosalind_6ATGCCATT>Rosalind_7ATGGCACT"
#separate each strand into a list using the delimeter separating each element by '>'
delimiter = '>'
COLLECTION_LIST = COLLECTION.split(delim... |
bc4410c9e00ba6aaa0bbf6570f9764763a8ad8d5 | zhaoxinlu/leetcode-algorithms | /Offer_book_problems/050firstNotRepeatingChar.py | 454 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Editor: Zhao Xinlu
School: BUPT
Date: 2018-02-26
Function: 第一个只出现一次的字符
"""
def FirstNotRepeatingChar(s):
numDic = {}
for i in range(0, len(s)):
if s[i] in numDic:
numDic[s[i]] += 1
else:
numDic[s[i]] = 1
for i in range(len(s)):
if... |
e0f15d96e9dfc397d04d68a53112f4a0a3014458 | Joao-Dezan/Exercicios-Python-Guanabara | /Py3Guanabara/ex057.py | 274 | 3.953125 | 4 | sexo = str(input('Informe o sexo [F/M]: ')).strip().upper()[0]
while sexo not in 'FM':
sexo = str(input('Dado inválido. Por favor informe o sexo [F/M]: ')).upper().strip()[0]
print('Sexo {} coletado com sucesso!'.format('Masculino' if sexo == 'M' else 'Feminino'))
|
34e99badbcb5e2c92c56fc7019529960153ddae2 | Modupeolawuraola/python_examples | /temp.py | 434 | 4.5625 | 5 | # Write a program that begins by reading a temperature from the user in degrees
# Celsius. Then your program should display the equivalent temperature in degrees
# Fahrenheit and degrees Kelvin. The calculations needed to convert between different
# units of temperature can be found on the internet.
t=float(input... |
221d7a8ffd613fa00af001b4fc9f15697e7ec4e1 | zeus-y/Algorithm | /algorithm/插入排序.py | 1,275 | 4.34375 | 4 | '''
插入排序(Insertion-Sort)的算法描述是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
算法描述
一般来说,插入排序都采用in-place在数组上实现。具体算法描述如下:
从第一个元素开始,该元素可以认为已经被排序;
取出下一个元素,在已经排序的元素序列中从后向前扫描;
如果该元素(已排序)大于新元素,将该元素移到下一位置;
重复步骤3,直到找到已排序的元素小于或者等于新元素的位置;
将新元素插入到该位置后;
重复步骤2~5。
'''
def insertSort(array):
for i in range(len(arra... |
b87672d6747c094c72685e4e266179f5b48ccc78 | dimitar-daskalov/SoftUni-Courses | /python_advanced/labs_and_homeworks/04_comprehensions_lab/04_flattening_matrix.py | 138 | 3.640625 | 4 | size = int(input())
matrix = [[int(num)for num in input().split(", ")] for row in range(size)]
print([x for row in matrix for x in row]) |
86cfd7c9be83dc5f5806eb223cd0c19bcaf943bd | brkyydnmz/Python | /Temel/recapDemo1.py | 273 | 3.59375 | 4 | # -*- coding: utf-8 -*-
# [] bir listedir.
lights = ["red","yellow","green"]
currentLight = lights[0]
print(currentLight)
if currentLight == "red":
print("STOP!")
if currentLight == "yellow":
print("READY!")
if currentLight == "green":
print("GO!") |
788463538e2b1f0336dad45a6ffbde9872c0500e | matthewcarcao/ICS3U_Class_Notes | /2D Lists.py | 472 | 3.71875 | 4 | a=[1,2,3]
b=[99,98,97]
newlist=[a,b]
print (newlist)
row_sum=int(input("What row would you like the some of?"))
sum = 0
if row_sum==1:
for i in newlist[0]:
sum = sum + i
elif row_sum==2:
for i in newlist[1]:
sum = sum + i
print(sum)
column_sum=int(input("What column would you like the some of?")... |
1c9c73817718a1279a0849967d1082e8fb983214 | gabriellaec/desoft-analise-exercicios | /backup/user_328/ch54_2020_03_30_23_14_05_266575.py | 196 | 3.828125 | 4 | def calcula_fibonacci(n):
f1= 1
f2= 1
contador=3
tamanho= len(n)
while contador <= tamanho:
f3= f1 + f2
f1= f2
f2= f3
contador += 1
return n |
985514d176437addcc2a549e84ee8e3f6f7efe85 | KaterinaMutafova/SoftUni | /Python Advanced/10. Exam_preparation/Exam_3ex_16_12_2020.py | 440 | 3.65625 | 4 | def get_magic_triangle (count):
matrix = []
for r in range(count):
line_length = r + 1
line = [1] * line_length
matrix.append(line)
for row in range(count):
for col in range(0, len(matrix[row]) -1):
if row >= 1 and row < len(matrix) - 1:
... |
27cfb9468d569e8acc2cb2cc43d70b4ecbb04eb8 | shivani-aradhya/Leetcode-DSA | /Interview Questions Practice/Leetcode week3/92 Reverse Linked List II.py | 725 | 3.84375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
if not head:
return head
if left == right:
... |
09cfbcd85bb31eeda566be5156fd863f6a5e7bdd | danghualong/MyAlogrithms | /alog/pre_mid_tree.py | 1,449 | 3.75 | 4 |
class TreeNode(object):
def __init__(self,x):
self.x=x
self.left=None
self.right=None
class Solution(object):
def __init__(self):
self.root=None
def buildTree(self, preorder, inorder):
if(preorder==None or inorder==None):
return Non... |
99f6727d5cc7be61e8ffb2621fc6c4f68878a9a5 | tanayz/ProPrac | /ip3.py | 1,045 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Find the first unique value from an unsorted array
Author : Tanay Chowdhury
"""
import time
input=[2,3,3,2,11,7,3,11,9,10,7,8,12,12,8,5,10,9,8,2,11]
t=time.time()
dc={}
for i in range(len(input)-1): #O(n)
if dc.has_key(input[i]):
dc[input[i]]+=1
else:
dc[input[i]]=1
f... |
6a479c7283797a5abea4a9a48fa5d87527228b27 | seeker8/python-exercises | /python_challenge/challenge/models/Person.py | 673 | 3.53125 | 4 | class Person:
def __init__(self, id=0, name="", age="", phone_number="", birthday=""):
self.id = id
self.name = name
self.age = age
self.phone_number = phone_number
self.birthday = birthday
def __str__(self):
person_str = 'ID: ' + str(self.id) + '\n'
per... |
12c0017dbc6ff6e17327dc9cf61472d35c4e961f | Trash-Bud/FPRO | /REs/RE11/Binary tree.py | 282 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 10 13:08:23 2019
@author: Joana
"""
def binary_tree(key, tree):
if tree[0] == key:
return tree[1]
elif key < tree[0]:
return binary_tree(key,tree[2]())
else:
return binary_tree(key, tree[3]())
|
67cf8722aa31dde1afcff23f2f7c2b7086539407 | Crisescode/leetcode | /Python/Tree/226. invert_binary_tree.py | 1,845 | 4.3125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# https://leetcode-cn.com/problems/invert-binary-tree/
# Invert a binary tree.
"""
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 ... |
247de5de9fdb2fe777006448b1e25c11b957e980 | g-quest/machine_learning_3 | /linear_regression.py | 4,659 | 3.71875 | 4 | # written in Python 3
import sys
import csv
import pandas as pd
def main():
# check that proper arguments were entered in command line
if len(sys.argv) != 3:
print('ERROR: two arguments required')
print('usage: python3 linear_regression.py linear_regression.csv <output_csv>')
sys.exit... |
7cc35e46f8560cc7bce2669c85fef5c2e60ec9a8 | arnavsoni231/byufinalproject | /tictactoe.py | 6,099 | 4.09375 | 4 | # Tic Tac Toe game
# This is two player game and each player can enter their move one by one
# This program will choose one of the play to go first randomly
import random
# This class has all the functions to manage Tic Tac Toe board functionality
class BoardClass():
def __init__(self):
self.board = [' '... |
ce7f8be35069ce786fa265ce57b30a991a627cdf | oustella/coding-exercises | /queue_linkedlist.py | 1,347 | 4.34375 | 4 | # OSL 02/12/2021
# implement a queue with linked list
# what is a queue?
# Think aobout people waiting in line. First come first serve (go).
# Dequeue: Remove the first in line.
# Enqueue: Add an element to the end of the queue.
class node():
def __init__(self, value) -> None:
self.value = value
s... |
306808e6cb0825448a6f16b96ddb220931dd4f98 | Dwyanepeng/leetcode | /isBipartite_785.py | 1,995 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File :isBipartite_785.py
# Author: PengLei
# Date : 2019/7/30
'''图'''
class Solution:
def isBipartite(self, graph):
a, b = set([]), set([])
d = {True: a, False: b}
flag = True
visited = set([])
for i in range(len(graph)):
... |
9aae985962bef0703835f89f80566f77a87260c5 | InfiniteGeo/python | /ex4.py | 462 | 4.09375 | 4 | #https://www.geeksforgeeks.org/turtle-programming-python/
import turtle #Inside_Out
wn = turtle.Screen()
wn.bgcolor("black")
skk = turtle.Turtle()
skk.color("white")
def sqrfunc(size):
while (1 < 101):
skk.fd(size)
turtle.forward(74 + 1)
turtle.right(472 + 6)
skk.left(90)
s... |
977c9073a0dd1f424dd8626cb14d6150c17d224c | vermashobhit1994/Python_Programs | /OOPs_Concepts/10_Constructor_In_Inheritance.py | 1,878 | 4.75 | 5 | #Program to understand how constructor or __init__() is called in multiple inheritance
#This is done in order in which class is inherited .
#Here we also understand use of super() i.e to access the parent class
class B:
#by the creation of class B constructor it will call it instead of class A
def __init__(self... |
18b93e215025f32c80476a315fe488d2cfb53993 | coreyarch1234/Data-Structures | /source/palindromes.py | 2,332 | 4.15625 | 4 | #!python
# Hint: use string.ascii_letters (all letters in ASCII character set)
import string
def is_palindrome(text):
"""A string of characters is a palindrome if it reads the same forwards and
backwards, ignoring punctuation, whitespace, and letter casing"""
# implement is_palindrome_iterative and is_pa... |
04df6f9af70319b9f668031793298b134acac851 | MMyungji/algorithm2 | /삼성SDS기본/1110_더하기사이클.py | 373 | 3.875 | 4 | def cycle(num):
global count
count+=1
first = num%10
if num<10:
second = num
else:
temp = num%10
num//=10
temp += num%10
second = temp%10
# print(2,second)
now = (first)*10+second
# print('now:',now)
if now == N:
return count
cycle(... |
6b855081f877c3fe549f25b86358d9a3bf968cd2 | andssuu/mestrado | /paa/atividade 3/1.py | 715 | 4.21875 | 4 | # Pesquisar sobre a Ordenação da Bolha (Bubble Sort): análise e implementação
'''
Análise
O Bubble sort é um dos mais simples algoritmos de ordenação. A ideia consiste
basicamente em percorrer um vetor e comparar dois elementos adjacentes e trocar
suas posições, caso o primeiro elemento seja maior que o segundo elemen... |
33636290308eaaaea5c8074d43ccf2ddfdaad807 | sahthi/backup2 | /backup_files/sanfoundry/file3.py | 333 | 3.8125 | 4 | #!/usr/bin/python
fname=raw_input("enter file name;")
l=raw_input("enter letter to be searched:")
k=0
with open(fname,'r') as f:
for line in f:
words=line.split()
for i in words:
for letter in i:
if(letter==l):
k=k+1
print("occurences of the letter:"... |
09b1d8a900cdca16cee944f40b6f2b6ca92ef1a6 | ChristNguyen/spark-playground | /python_basics/IfElse.py | 112 | 4.0625 | 4 | x = True
if x:
print("it is true")
elif x == 'test':
print("it is elif")
else:
print("it is false") |
648453948c3fb193ab759e3c0387e9831d5fe7eb | dipanwita2019/ml_projects | /02_linearregression/linreg.py | 850 | 3.71875 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('seaborn-deep')
# Importing the dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
# Training/testing
from sklearn.model_selection import train_test_split
X_train, X_test,... |
aa39e7715ca5fd77d798664ef38f03981edd3fdd | pszostek/lamaniec_cracker | /wyprawa.py | 5,061 | 3.65625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
def reduce_word(word):
ret = {}
for letter in word:
try:
ret[letter] += 1
except:
ret[letter] = 1
return ret
def is_feasible(word, letters):
tricks = {u'ą':'a', u'ę':'e', u'ó':'o', u'ł':'l',u'ć':'c',u'ś':'s', u'ż':'z', u... |
c47141ec4921596b63ae68bcfd37a4ccc0992361 | YiqunPeng/leetcode_pro | /solutions/83_remove_duplicates_from_sorted_list.py | 502 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
"""Linked list
Running Time: O(n) where n is the length of the list.
"""
h = head
... |
f17ad6779c33c2fc93de20819c7f12d932066916 | hahah4/lit_lista | /exe_01.py | 1,057 | 3.640625 | 4 | p = {}
banco =[]
soma_idades = 0
guarda_pos= 0
total_m = 0
for c in range(1, 5):
p['nome'] = str(input(f'Digite o nome da {c}a pessoa:'))
p['idade'] = int(input(f'Digite a idade da {c}a pessoa:'))
soma_idades += p['idade']
while True:
p['sexo'] = str(input(f'Digite o sexo (M ou F) ... |
79eb653e6d899e2ae8391af8397e3a1209085f58 | hari1811/Python-exercises | /Quiz App/quiz_application.py | 1,097 | 4.1875 | 4 |
''' Quiz Application
This is a standard quiz application that presents a set of carefully curated
questions to the users (a questionnaire), allows them to answer the same, and
displays the correct answer if they are wrong. Each test displays the
final score of the user.
The application has an account creat... |
127765e5a48f02ddc26adcb09ff967e8dcec5d1d | hweavn/ITS-250-Python | /ITS-250 Project (Final).py | 13,139 | 4.0625 | 4 | ##Hannah Weaver and Michelle Whitlock
# A list of items that the bakery offers
list_of_items = ["Cookie", "Muffin", "Brownie", "Croissant", "Cupcake", "Slice of Cake"]
# Have to globalize these variables so they can be called outside of their functions
amount_cookie = 0
amount_muffin = 0
amount_brownie = 0
amo... |
f2df5ca1e0f47be584f77de58f0f14b4427afe30 | smirnoffmg/codeforces | /465A.py | 263 | 3.5 | 4 | # -*- coding: utf-8 -*-
n = int(raw_input())
number = raw_input()
diff = 0
one = True
for i in xrange(n):
if number[i] == '1' and one:
diff += 1
one = True
if number[i] == '0' and one:
diff += 1
one = False
print(diff)
|
cb2b7a5f28fa913488b57dbcf0496b03313e3945 | ucfdesign/ComputeWorkshop-Fa17 | /src/W02/loops.py | 325 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
loops.py
Josh Kaplan
jk@ucf.edu
Here is an example of a loops in Python
"""
# This is an example of a for-loop
for i in range(1, 10):
print(i)
# This is an example of a while-loop
i = 1
while i < 10:
print(i)
i += 1 # This is the same ... |
3de59173777973f7869cac05a1a322bc764683d4 | hero881011/VIP5 | /python/class6/test3.py | 637 | 3.5625 | 4 | # coding=utf-8
def sum_xy(x=1, y=2):
print(x)
print(y)
z = x + y
return
# 函数的调用
print(sum_xy(3, 22))
def test_args(a, b, c=None, d=None, *args, **kwargs):
print(a)
print(b)
print(c)
print(d)
print(args)
print(type(args))
print(kwargs)
print(type(kwargs))
test_args(... |
9e697741b35128b38f62ad772e5251df86b79259 | naren2605/hackerrankpy | /hker/cut_tree.py | 958 | 3.546875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
visited=dict()
def getneighbours(edgelist,v):
for key in edgelist[v]:
yield key
def dfs(graph,start):
count=0
stack=list()
stack.append(start)
while len(stack)!=0:
v=stack.pop()
if not visited.ha... |
aa5091453ac2bd4eb01d823f63f264f61627edfe | lakshyarawal/pythonPractice | /Arrays/maximum_appearing_element_ranges.py | 1,067 | 4 | 4 | """ Given N ranges, find the maximum appearing element in these ranges L: [ 1, 2, 5, 15 ] R: [ 5, 8, 7, 18 ]. Ranges are
1-5, 2-8, 5-7, 15-18"""
"""Solution: """
def max_appear(left_array, right_array) -> int:
n = len(left_array)
prefix_arr = [0] * 1000
for i in range(n):
prefix_arr[left_arr... |
1e97b880b03136f3221b91d9dd0911a017759d1d | xuefengsi/machine-learning | /8_27.py | 2,733 | 3.609375 | 4 | '''def findArrayMex(A, n):
# write code here
m = max(A)
for i in range(1,m):
if i not in A:
return i
'''
'''
def findMaxDivision( A, n):
import numpy as np
m = max(A)
h = 0
B = []
C = []
for i in range(0,m):
B.append(h)
for i in range(0,n):
... |
a7efe3deb38aa7aa21b2a360e33bbf64f53f037f | katrinamo/Scripts-Snips | /Python-Snips/whoFollows.py | 2,497 | 3.6875 | 4 | # Author: Katie Long
# Description: Figure out who follows you back. If they don't follow back, you
# have an option to unfollow. Doesn't support batch unfollowing
# or unfollowing of those not on the list.
# Based on scripts by jamiesonbecker (http://pastebin.com/CxUDMtMi) & audreyr
# (http... |
3462361cd55b20edecf9e1d25aa9e0fb1866754a | liguanlue/Q-pathplanning | /train.py | 910 | 3.5625 | 4 | from collections import OrderedDict
from pprint import pprint
grid_size=(3,3)
bounds = (1, 1, grid_size[0], grid_size[1])
intersections = OrderedDict()
tij = OrderedDict()
Q_table = OrderedDict()
for x in range(bounds[0],bounds[2]+1):
for y in range(bounds[1],bounds[3]+1):
intersections[(x,y)] = x+... |
db79e3ffaba292b8b236578215f5506c3b0dbd6b | CodeKul/Python-Weekend-11am-1pm-Sep-2019 | /Exercise3.py | 329 | 4.03125 | 4 | # Write a function to conver decimal number to binary
# 10 - 1010
def dec_bin(no):
bin = 0
mul = 1
while no > 0:
dig = no % 2
no = int(no / 2)
bin = (mul * dig) + bin
mul *= 10
return bin
dec_no = int(input('Enter decimal no: '))
bin_no = dec_bin(dec_no)
print('Binary:'... |
0668fcdaf1e4d7869745f0094011509923ff36fc | lgwakano/ISS | /203_Python_LABS/Lab1/m1p4.py | 1,914 | 3.5 | 4 | # @filename: [m1p4]
# @author [Luiz Wakano]
# @course ITSC203
# @create date 2020-01-20 12:30:29
# @details [description]
# @resources: https://www.pythonforbeginners.com/basics/list-comprehensions-in-python
# https://stackoverflow.com/questions/10037115/comparing-a-float-and-an-int-in-python
marks = [79,66,50,45,45,5... |
dcdf2ee7bbf4e337364230df08b49598c8e1e225 | feisal-Codes/learning-python-exercises-think-python-book | /classes.py | 1,050 | 4.03125 | 4 |
import copy
import math
class Point:
"""Represents a point in 2-D space.
attributes: x, y
"""
class Rect:
"""Represents a rectangle.
attributes: width ,height ,corner
"""
def distance_between_points(p1,p):
distance=math.sqrt(math.pow((p1.x - p.x),2) + math.pow((p1.y- p.y),2))
r... |
17b8ae8260e2c69b3fe3b59fd2575919ab02356a | XiaoxiaoWang87/LaneFinding | /examples/example.py | 725 | 3.5625 | 4 | import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
image = mpimg.imread('test.jpg')
print("This image is: ", type(image), 'with dimensions: ', image.shape)
ysize = image.shape[0]
xsize = image.shape[1]
color_select = np.copy(image)
print color_select[1]
print color_select[1].shape... |
1080f386e9408758840106530b27ba7337d86a0c | chowsychoch/Programming-1- | /p7/p7p5.py | 256 | 4.09375 | 4 | # Set the range between 1 and 10000.
# if number is divided my 3 or 5
#print sum of dividable number
for i in range (1,10000):
print('number', i)
if i % 3 == 0 or i % 5 == 0:
total = i / 3 + i / 5
print('Total:', int(total)) |
8067f9ccf808321f9fac53bdca648ab4ce117067 | sotrnguy92/udemyPython | /udemy4/pythonDataTypesAndVariables/variablesHomework2.py | 687 | 4 | 4 | firstStudentName = input("Enter the student's name: ");
firstStudentId = int(input("Enter the student ID: "));
firstStudentGrade = float(input("Enter the student's grade: "));
secondStudentName = input("Enter the second student's name: ");
secondStudentId = int(input("Enter the second student ID: "));
secondStudentGra... |
71b518fc826e30db92f44aefaf3a5d467e61d714 | omkar6644/Python-Training | /python_csv_read.py | 232 | 3.734375 | 4 | #import csv module
import csv
#open a csv file in read mode
with open("emp.csv",'r')as f:
#call reader method on file
r = csv.reader(f)
#convert to list
data = list(r)
print(data)
print(type(data)) |
593bee58c71e4496e3c496827c4c3689a4d834ef | JLee21/tech-prep | /code-problems/hash_table_problems/prison_cells.py | 3,575 | 4.0625 | 4 | """
There are 8 prison cells in a row, and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
Otherwise, it becomes vacant.
(Note ... |
d432214ede8adb45237372841ca624c897d945ba | AmanSingh1611/Sorting-Algos | /bubblesort.py | 286 | 3.921875 | 4 | def bubblesort(arr):
indexing_length=len(arr)-1
Sorted = False
while not Sorted :
Sorted=True
for i in range(indexing_length):
if arr[i]>arr[i+1]:
Sorted=False
arr[i],arr[i+1]=arr[i+1],arr[i]
return arr
arr =list(map(int,input().split()))
print(bubblesort(arr))
|
5aaafd89b3a36e960a728a670e2dfc9f3124006d | QIAOZHIBAO0104/My-Leetcode-Records | /70. Climbing Stairs.py | 1,042 | 4 | 4 | '''
https://leetcode.com/problems/climbing-stairs/
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
... |
d457228bccc6e1460911c811160fa5eccfd9caf5 | Aarif123456/foobar | /3/b/soution.py | 1,396 | 3.5 | 4 | def solution(n):
coefficients = [1]+[0]*n
for i in range(1, n+1):
for j in range(n, i-1, -1):
coefficients[j] += coefficients[j-i]
return coefficients[n]-1
# Your code here
###############################################
# Code below is not submitted
import unittest
class sTest(unitte... |
f740415864f4bec4ca35d6717d6a54bb12632d2c | k2ev/linkedlist | /__main__.py | 757 | 4.09375 | 4 | from StacksQueues import *
def main():
print("Stack")
a = LinkedListStack()
a.append(10)
a.append(20)
a.append(30)
print(len(a))
print(a)
print(a.top())
print(a.first())
print(a.last())
a.pop()
print(a)
print("Queue")
a = LinkedListQueue()
a.append(10)
... |
920163290c0afb550e65bcc4b6fceeb30b5fb18d | Niranjan-Ananth/DS-and-Algorithms | /Data_Structures/circular_linked_list.py | 3,155 | 3.734375 | 4 | class Node:
def __init__(self, element) -> None:
self.data = element
self.next = None
class CircularLinkedList:
def __init__(self) -> None:
self.__start = None
self.__tail = None
def insert_node_at_beginning(self, element):
node = Node(element)
if self._... |
f3d9d77f16ce027e7227bade9ae36bf4831d1f15 | VimanyuAgg/code-morsels | /CTCI/ch16_8_english_int.py | 1,626 | 3.59375 | 4 | def numberToWords(num: int) -> str:
ones = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve",
"Thirteen", "Fourteen", "Fifteen", "Sixteen",
"Seventeen", "Eighteen", "Nineteen"]
tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", ... |
54ae297a37b8cf7a7c7f04666602e00bbf467394 | natedileas/imsciutils | /core/ImageViewer.py | 3,718 | 3.84375 | 4 | import cv2
import numpy as np
class ImageViewer(object):
"""
Class to simplify displaying images using opencv windows. Also has
functionality to resize images automatically if desired
On some systems (or opencv builds), openCV requires a waitkey to be
called before displaying the image. This func... |
92cb308a714a437d083ad682032ceea2035d8881 | MacondoRain/DataAnalysist-Python | /CH02Pandas__Part02.py | 13,362 | 3.90625 | 4 |
# coding: utf-8
# In[1]:
'''
【课程2.8】 时间模块:datetime
datetime模块,主要掌握:datetime.date(), datetime.datetime(), datetime.timedelta()
日期解析方法:parser.parse
'''
# In[6]:
# datetime.date:date对象
import datetime
today = datetime.date.today()
print(today,type(today))
print(str(today),type(str(today)))
# datetime.date.to... |
5922b80d5b6a79d54e4d7ac36f7783b24db9762e | LarissaMidori/curso_em_video | /exercicio044.py | 1,317 | 3.90625 | 4 | ''' Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento:
– à vista dinheiro/cheque: 10% de desconto
– à vista no cartão: 5% de desconto
– em 2x no cartão: preço normal
– 3x ou mais no cartão: 20% de juros '''
print(f'{" LOJAS DECOR ":=^40}')
p... |
96d2d5cc01d2b726d4689a5cda5266c451a48112 | b2dl-uit/GTx-CS1301xII-ControlStructures | /coffe-balance.py | 813 | 4.21875 | 4 | cafe = "Octane"
balance = 7.5
# - Octane: $6
# - Galloway: $5
# - Starbucks: $4
# - Revelator: $3
# - Dunkin: $2
if cafe == "Octane" and balance >= 6:
print("With {} dollars, I can buy coffee at {}".format(balance,cafe))
elif cafe == "Galloway" and balance >= 5:
print("With {} dollars, I can... |
4a8a8c681bf64c165ae7c1d12bc79a4a0c250518 | celine5/GUVIrepo | /leap.py | 182 | 3.859375 | 4 | year = int(input())
if year % 4 == 0 and year % 100 != 0:
print("true")
elif year % 100 == 0:
print("false")
elif year % 400 ==0:
print("true")
else:
print("false")
|
e451a7906a8594c39fffce372aeb1f29e223446c | nithin05092000/MULESOFT | /Movies.py | 1,184 | 3.984375 | 4 | import sqlite3
from sqlite3.dbapi2 import Cursor
connection = sqlite3.connect("movies1.db")
Cursor = connection.cursor()
command1 = """
CREATE TABLE [MOVIESTABLE](
[TITLE] NVARCHAR(100) NOT NULL,
[ACTOR] NVARCHAR(100) NOT NULL,
[ACTRESS] NVARCHAR(100) NOT NULL,
[DIRECTOR] NVARCHAR(100) NOT NULL,
[YEAR] INTEGER(10)... |
197577c25cd8219308c67ce2423ddaa7019fc44b | vipinvkmenon/canddatastructures_python | /chapter1/example3.py | 386 | 3.96875 | 4 | #Chapter 1.3
# INPUTTING THE DATA
def main(): # Main Function
# Variables Declaration
i, j, k = 0, 0, 0 # Initialised
i = int(raw_input()) # Raw input is for keyboard input
j = int(raw_input())
k = i + j # Find sum
print("Sum of the two numbers is "), # Print Function (note the comma )
... |
821a795b81cd92048b058c980155ab0225d5adb0 | DAVIDCRUZ0202/Computer-Architecture | /notes.py | 12,908 | 3.9375 | 4 | """
Number Bases
_________________________________
It's the "language" that a number is written down in
Douze(french) == (english)Twelve
same thing!!
1100(binary) == 12
same thing!!
base 2: binary
base 8: Octal(rarely used)
base 10: decimal (what we know from grade school)
base 16: hexadecimal "hex"
base 64: base ... |
35d8db75e15ea20354472a57306ad52a93a5a49e | jodr5786/Python-Crash-Course | /Chapter 8/8-12_Sandwiches.py | 311 | 3.71875 | 4 | def make_sandwich(*toppings):
"""Summarizes a sandwich being made."""
print("Making a sandwich with the following toppings:")
for topping in toppings:
print("- " + topping)
make_sandwich('salami')
make_sandwich('provolone', 'ham')
make_sandwich('swiss', 'turkey', 'mayo', 'pickles') |
852fc3cba12c11c5825db50cc171386da989806f | Ashokkommi0001/Python-Patterns-Symbols | /right_triangle.py | 234 | 3.859375 | 4 | def right_triangle():
for row in range(6):
for col in range(6):
if (col==5 or row==5) or row+col==5:
print("*",end=" ")
else:
print(end=" ")
print()
|
88f80670db2be51189ae84e8ab792676f556670a | Fernandoramos24/semana6 | /semana06/estudiandoifanidado.py | 807 | 3.796875 | 4 |
#Si gasto hasta $100, pago con dinero en efectivo. Si no, si gasto más de $100 pero menos de $300, pago con tarjeta de débito. Si no, pago con
#tarjeta de crédito
#obtencion de datos
compra = int(input("coloque el dato de su compra"))
# en el primer if estamos comparando todos aquellos datos
# que sean menores o igua... |
c1f777ba0fc1343cd551243e90ef4fab563637b2 | Austin-Bell/PCC-Exercises | /Chapter_8/t_shirt.py | 472 | 4.09375 | 4 | """Write a function called make_shirt() that accepts a size
and the text of a message that should be printed on the shirt."""
"""def make_shirt(size,message):
print("This shirt should be in a size " + size + " and have the message " + message + " printed on it.")
"""
# 8-4 Large shirts
def make_shirt(size = 'larg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.