blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f9b052a355ee2f7ee5acf0bac6bd11a04df7c9eb | boltnev/Exercises | /strings/isomorphic.py | 890 | 3.5625 | 4 | import unittest
# O(N)
def is_isomorphic(a, b):
if len(a) == len(b):
def get_unified_mapping(a):
mapping = {}
unified_arr = []
counter = 0
for l in a:
if l not in mapping:
mapping[l] = counter
counter +... |
75b0e9718708251a750c76256d6318ab80f4d6b1 | jameswmccarty/AdventOfCode2017 | /day22.py | 10,298 | 3.5 | 4 | #!/usr/bin/python
"""
--- Day 22: Sporifica Virus ---
Diagnostics indicate that the local grid computing cluster has been contaminated with the Sporifica Virus. The grid computing cluster is a seemingly-infinite two-dimensional grid of compute nodes. Each node is either clean or infected by the virus.
To prev... |
a6a408ed86b69c6aac3a5b1d27fa0cb46a64e6dc | AlexandraFil/Geekbrains_2.0 | /Python_start/lesson_5/lesson_5.1.py | 521 | 4.09375 | 4 | # 1. Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем.
# Об окончании ввода данных свидетельствует пустая строка.
while True:
line = input("Введите строку: ").split()
if len(line) == 0:
break
with open("new_1.txt", "a") as f:
for i in ran... |
5b946a75f1bda29059f2e1b6719c3a2438e4e40a | Botgar-Org/assignment-2-afriendsmoq | /listserv.py | 1,014 | 3.9375 | 4 | import csv, os, sys
def create_lists(csv_file):
with open(csv_file, 'rU') as f:
reader = csv.reader(f, delimiter= ',')
for row in reader:
#get grade level initials from col 4 (BA, BFA, MFA, etc.)
grade_level = row[4].split('.')
#concatenate first and last name from col 2 and 3
name = row[2] + " " + ro... |
e427d1d8f8f57c9696b27388f88cea1d4f117e09 | amarmulyak/Python-Core-for-TA | /hw05/akhomi/Task1.py | 486 | 4.09375 | 4 | # # # Генерується список випадкових цілих чисел. Визначається, скільки в ньому парних чисел, а скільки непарних.
import random
a = []
pair_a = 0
not_pair = 0
for i in range(10):
a.append(int(random.random() * 100))
print(a)
even = 0
odd = 0
for number in a:
if number%2 == 0:
even += 1
else:
... |
2ad8e0c96c3ff2a27ad6c2c4bd065146bee6b1e3 | BrandConstantin/python | /Beginner/08_functions/Calculator.py | 1,145 | 4.25 | 4 | #Calculator
# add
def add(num1, num2):
return num1 + num2
# substract
def substract(num1, num2):
return num1 - num2
# multiply
def multiply(num1, num2):
return num1 * num2
# divide
def divide(num1, num2):
return num1 / num2
## Operations
num1 = int(input("What is the first number that you wanna use?... |
f759d12f98b50c6c430ab5e98c037a3cff52778f | AnnaGeorge-J/FST-M1 | /Python/Activities/Activity2.py | 162 | 4.28125 | 4 | number = int(input("Enter a number: "))
mod = number % 2
if mod > 0:
print("The number you entered is odd")
else:
print("The number you entered is even")
|
120517a5539a044db7bda92fceebd5fc59ff2c9e | dsasse07/learning-python | /assignment-2/q3-subtract.py | 542 | 4.1875 | 4 | '''
Write a program in the file subtract_numbers.py that reads two real numbers from the user and prints the first number minus the second number.
$ python subtract_numbers.py
This program subtracts one number from another.
Enter first number: 5.5
Enter second number: 2.1
The result is 3.4
'''
def main():
print('Th... |
eefb5effbb12b148676e9e8e298141dfa214653c | jeanettehead/easy-functional-python-materials | /map.py | 318 | 4.125 | 4 | #map
def square(x):
return x**2
print square(5)
#print square of every number between 0 and 10
print map(square, range(10))
print map(lambda n: n**2, range(10))
#print square of every number that is a multiple of 3 or 5 between 0 and 20
print map(lambda n: n**2, filter(lambda n: n%3==0 or n%5==0, range(20))) |
dfbca3d7033f633002771dc498355ee1778b00c8 | davidjuliancaldwell/ScientificSupercomputing | /astro598algorithms/davidcaldwell_hw5/priorityQueue.py | 1,719 | 3.890625 | 4 | #!/usr/bin/python
class priorityQueue:
def __init__(self,M):
self.N = 0
self.MAX = M
self.a = [0]*M
def insert(self,i):
self.N = self.N + 1
if(self.N >= self.MAX):
raise Exception("Would exceed size of array")
self.a[self.N] = ... |
7eac60394bf614f18634c5ca15d38ae3f856188d | shchun/udacity_work | /eulerian_tour.py | 4,638 | 3.71875 | 4 | #!/usr/bin/env python
def get_all_node(graph):
allnode = set([])
for edge in graph:
allnode.add(edge[0])
allnode.add(edge[1])
return allnode
def find_eulerian_tour(graph):
eulpath = []
odd_node = []
tour = []
allnode = get_all_node(graph)
#print 'allnode = ', allnode
# make node - degree dictionary
... |
7db6c4f113609bd0e88a2391b14d38326b516243 | Shamsdamani21/CIS106-Jack-Samson | /Assignment 6/Activity 2.py | 1,333 | 3.921875 | 4 | # A simple program that tells you your age in months days and seconds
yearsinayear = 1
monthsinayear = 12
daysinayear = 365
hoursinayear = 365 * 24
secondsinayear = 365 * (24 * (60 * 60))
def input_func():
print("input age in years")
age = float(input())
return age
def processing_func1(age... |
21a8061852b730df752a97db4697f5bbca84891d | Semisvetiiik/My_python | /1.syntax/3.collection.py | 2,712 | 4 | 4 | # *** list ***
# сощдание пстого списка
my_list = []
my_list_2 = list()
# добавление объекта (в конец списка)
my_list.append(100)
my_list.append(77)
my_list.append("A")
my_list.append([1,2,3])
# обращение к элементам списка
my_list[0] = 5
my_list[-2] = 'B'
# чиение значений
element_value = my_list[1]
# удаление з... |
051d43fe1efe36f09f5b8bd6eee99528124995d7 | harshsri2208/Machine-Learning-Lab-7th-Sem | /ML Assign 7/ML Assign 7/Assign7.py | 7,962 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Comparing Distance Based Classifiers
# ## Submitted By Harsh Srivastava
# ## 117CS0755
# ### importing libraries
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import normalize
# ### function to calculate eucli... |
2394fcc45de5036a702479771840d78471881474 | hectormanfredi/PythonExercicios | /ex006.py | 275 | 3.828125 | 4 | # Crie um algoritimo que leia um número e mostre o seu dobro, triplo e a raiz quadrada
n = int(input('Digite um número: '))
print('O dobro de {} é {}.\n O triplo de {} é {}.\n E a raiz quadrada de {} é {:.2f}.'
.format(n, n * 2, n, n * 3, n, pow(n, (1/2))))
|
d1303d03bd2776feaf3767ded4cead39f96d80e9 | SomyaBansal1998/pythoncode.repo | /leastfrequentchar.py | 138 | 3.78125 | 4 | from collections import Counter
str1=input()
res=Counter(str1)
res=min(res,key=res.get)
print("Least frequent character is:"+ str(res))
|
032e19aec5dabed82e2a7a5b792a3463853cbd5b | dhita-irma/miniprojects | /numbers/change_return/change_return.py | 1,336 | 4.3125 | 4 | # Change Return Program - The user enters a cost and then the amount of money given.
# The cost has to be lower than 2000.
# The program will figure out the change and the number of
# 100, 200, and 500, and 1000 needed for the change.
cost = int(input("Enter the cost: "))
money_given = int(input("Enter the money given... |
ab9a3ae65aa420321b63bb6a724fd88359cfb628 | JonDGS/Intro-y-Taller | /Recursion de pila/repetidosconlambda.py | 426 | 3.703125 | 4 | def lista(lista1, num):
if isinstance(lista1 ,list) and isinstance(num, int):
x = lambda num1, num2: num1 == num2
return detectar(lista1,num, x)
else:
return 'No se digito una lista'
def detectar(lista1,num1,esto):
if lista1 == []:
return 0
if esto(lista1[0], num1):
... |
48f87f9ec791cbbf110f9552337ad5ad7ed13116 | ronniebm/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 1,936 | 3.984375 | 4 | #!/usr/bin/python3
""" square.py module"""
from models.rectangle import Rectangle
class Square(Rectangle):
"""
Rectangle Rectangle.
Inheritance: from Base Rectangle.
-----------
"""
def __init__(self, size, x=0, y=0, id=None):
"""
This function create instances of an
... |
a4569633e9f170ae7bc98711be014b9bb77980bd | hansenliman/Fun-Coding-Challenges | /Implement a Sparse Array.py | 924 | 3.8125 | 4 | """
Problem taken from Daily Coding Problems.
You have a large array, most of whose elements are zero.
Create a more space-efficient data structure, SparseArray, that implements the
following interface:
- init(arr, size): initialie with the original arge array and size.
- set(i, val): update index at i to b... |
7fb0d815060c0c18c4a5c4e1ff465dc54f324d61 | vilem-nachtmann/malgym_programovani | /fibonacci.py | 280 | 3.546875 | 4 | seq = []
n = 0
F = 0
nMax = int(input("Nejvyšší počítaná pozice v posloupnosti: "))
while n <= nMax:
if n == 0:
F = 0
elif n == 1:
F = 1
else:
F = seq[n - 1] + seq[n - 2]
seq.append(F)
print(str(F))
n = len(seq)
|
7611f5aaef6fa332b6e272b2bcaef14bf547e3d0 | pawarspeaks/HackFest21 | /Patterns/leftArrowPattern.py | 263 | 3.75 | 4 | #left-arrow pattern
n=int(input())
st=2*n
for i in range(n):
for j in range(st):
print("*",end=" ")
if i!=n-1:
print()
st=st-2
for i in range(n+1):
for j in range(st):
print("*",end=" ")
print()
st=st+2 |
1a32f1ec8f48b7764b6f88e612eb328a4c3b47b5 | gheckojuandup/WB372 | /neville.py | 678 | 3.75 | 4 |
def neville(x_data, y_data, x):
"""p = neville(x_data, y_data, x)
Evaluate the polynomial interpolant p(x) that passes through the
specified data points by Neville's method."""
n = len(x_data)
p = n*[0]
for k in range(n):
for i in range(n-k):
if k == 0:
p[i]... |
f7acaf9db8a709cce08d508e872d765a2fd97490 | kid1988/ands | /ands/algorithms/dp/rod_cut.py | 7,379 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Author: Nelson Brochado
Creation: 30/08/15
Last update: 18/11/2016
## References:
- http://www.radford.edu/~nokie/classes/360/dp-rod-cutting.html
- Introduction to Algorithms (3rd edition) by CLSR
- Slides by prof. E. Papadopoulou
"""
import sys
def recursive_rod_... |
f4f4a9fc92a67ea250e36f5ef3e86435d5ba9f91 | KeiSoto/Agenda | /agenda.py | 1,028 | 3.671875 | 4 | import csv
class agenda:
def __init__(self):
print 'Menu\n'
print '1 Ver Agenda'
print '2 Insertar'
print '3 Salir'
self.opcion = int(raw_input('Ingrese la opcion que desee:\t'))
if self.opcion == 1:
with open('data.csv','r')... |
4346dafdec6049ae47d53c3c51fe7998280a32e8 | Sen2k9/Algorithm-and-Problem-Solving | /leetcode_problems/110_Balanced_Binary_Tree.py | 1,405 | 4.15625 | 4 | """
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
... |
6ace197ae9a8f78d22a41af5cfd77c2f69516635 | KritoCC/Sword | /ex14.py | 1,258 | 3.875 | 4 | # 习题十四
from sys import argv
script, user_name = argv
prompt = "> "
# 我们将用户提示符设置为变量prompt,这样就不需要在每次用到input时反复输入提示用户的字符了。
# 而且,如果要将提示符修改成别的字符串,只要改一个位置就可以了。
print("Hi %s, I'm the %s script" % (user_name, script))
print("I'd like to ask you a few question.")
print("Do you like me %s?" % user_name)
likes = input(prompt)
... |
b2d35e79ad9bb35a98c23ac5046734259f6c092c | colinrodney/python | /codingbat/string-1/make_abba.py | 171 | 3.625 | 4 | def make_abba(a, b):
''' function returns strings concatenated together in following order: abba,
Ex. make_abba('hi','bye') --> hibyebyehi '''
return (a+b) + (b+a)
|
60ce64c026c5a3038907174f24fe51dfdad8a94b | LeonMac/Principles-of-Data-Science_forPython3 | /P111_SND.py | 734 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#import random
import numpy as np
#import pandas as pd
from matplotlib import pyplot as plt
def normal_pdf(x, mu=0, sigma=1):
return (1./np.sqrt(2*3.14159*sigma**2) )* 2.718**( -(x-mu)**2/(2*sigma**2) )
x_values = np.linspace(-5,5,100)
y_values = [normal_pdf(x) for ... |
f69ac671207c7f9fa80d078e0b53e963ab629b87 | Shogo-Sakai/everybodys_ai | /math_training/exponential_functions.py | 192 | 3.546875 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-5, 5, 0.1)
# y = 2^x
y_2 = 2**x
# y = 3^x
y_3 = 3**x
print (x)
print (y_2)
plt.plot(x, y_2)
plt.plot(x, y_3)
plt.show()
|
c932b0be176a29ed44a91c6c5cc9de6b1308ff10 | yaoyuan0553/BertContextBasedEmbedding | /main.py | 2,451 | 3.5 | 4 | """
A program to load dictionary txt file and extract similarity between given words
Usage:
main.py --dict-src=<file> --bert-src=<dir> [options]
Options:
-h, --help show this message
--dict-src=<file> file path to the dictionary file to be read from
--bert-src=<dir> directory... |
8a32b559983080b6997082c139d16a143845c923 | YounessTayer/Tk-Assistant | /squirts/boxes/combo_box.py | 1,261 | 3.84375 | 4 | """Combobox demo.
Stand-alone example from Tk Assistant.
Updated March 2021
By Steve Shambles
stevepython.wordpress.com
"""
import tkinter as tk
from tkinter import messagebox
from tkinter.ttk import Combobox
root = tk.Tk()
root.title('Combobox demo')
# Callback
def clkd_btn():
"""... |
bcbf333e5af318b8fd88269b39cffa340f265798 | WuLC/LeetCode | /Algorithm/Python/215. Kth Largest Element in an Array.py | 1,421 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# @Author: WuLC
# @Date: 2016-06-07 15:24:56
# @Last modified by: WuLC
# @Last Modified time: 2016-06-07 15:25:08
# @Email: liangchaowu5@gmail.com
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: in... |
3fb2b5b841f6f113b80519af83709ee0e63e77b1 | georgezouq/Python-Algorithm | /TP-Growth/tree_building.py | 1,752 | 3.578125 | 4 | #coding=utf-8
class Node(object):
"""Node类 作用:开辟一个树节点"""
def __init__(self,data=-1,count=0,parent=None):
"""Node类的初始化,一个节点信息包括:项的值,计数,父亲节点,所有孩子节点"""
self.data = data
self.count = count
self.parent = parent
self.children = {}
class Tree(object):
"""tree_growth 类 作用:建... |
70ee75995e82d89c626fcf96f05e070db3340b3c | Achyut21/BasicStudentClass_python | /main.py | 1,307 | 3.953125 | 4 | class student:
def __init__(self, id, name, mid1_marks, mid2_marks, quiz_marks):
self.id = id
self.name = name
self.mid1_marks = mid1_marks
self.mid2_marks = mid2_marks
self.quiz_marks = quiz_marks
def result(self):
if self.total() >= 80:
print("Your ... |
de999010fc9a642d72bfef624778d48104efbae2 | sevgibayansalduzz/Algorithm-Design-and-Analysis | /hw4/part4.py | 2,222 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 28 09:43:08 2018
@author: sevgi
"""
# takes as input the list of n people and the list of pairs who know each other, and outputs the best choice of party invitees.
def partyInvitees(people,pairs):
output=[]
known=[]
#take a person and calculate that ... |
132877f639e5a0ca0ae3c78d5b930af3dc2e7236 | XiancaiTian/Leetcode | /q88.py | 921 | 3.78125 | 4 | class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
if m == 0:
nums1[:n] = nums2
... |
7b3bd0c249b8f4599732a6792c33aa6016dd73ae | PSFREITASUEA/padroes-de-projeto | /Line Up - Padroes/Flyweight/main.py | 1,715 | 4.125 | 4 | from abc import ABC, abstractmethod
class Object(ABC):
@abstractmethod
def display(self):
pass
class Tree(Object):
def __init__(self, x_cord, y_cord, age):
self.x_cord = x_cord
self.y_cord = y_cord
self.age = age
def get_x_cord(self):
return ... |
b4ee969d73b69351044266531e345326397d51be | FabrizioFubelli/py-math-sequences | /fibonacci.py | 1,101 | 3.765625 | 4 | #!/usr/bin/env python2
"""
Calculates the nth number of Fibonacci sequence
Reference: https://github.com/Dvd848/CTFs/blob/master/2018_picoCTF/be-quick-or-be-dead-2.md
"""
from ctypes import *
import numpy as np, sys
np.seterr(all="ignore")
class Memoize(object):
def __init__(self, func):
self.func = fun... |
a1d40dc66340262213219edcfb6092f778d8583e | Yuhsuant1994/leetcode_history | /solutions/set_mismatch.py | 977 | 3.828125 | 4 | """
You have a set of integers s, which originally contains all the numbers from 1 to n.
Unfortunately, due to some error, one of the numbers in s got duplicated to another number
in the set, which results in repetition of one number and loss of another number.
You are given an integer array nums representing the da... |
36507b00b4c438782f262509518890af94c634a9 | itsparth20/Data-structure-and-Algorithms | /Python/findsortestdist/findsortestdist.py | 1,231 | 3.96875 | 4 | # Q1. Given a string. Find distance of all characters from a target character.
# For example, "Google", target character= 'g', then result will be [0,1,1,0,1,2]
import sys
def find_sortest_dist(input, ch):
if input is None or input.strip() == '':
return []
lower_ch = ch.strip().lower()
lower_in... |
5e71b7765a962e8ef392cba580df8c74357916bd | bangoc123/PythonPractice | /theme.py | 406 | 3.5625 | 4 | # 3.5 from tkinter import *
from Tkinter import *
root = Tk() #create new window
root.wm_title("Training X Team")
label = Label(root,text="username")
label.pack()
nameInput = Entry(root)
nameInput.pack()
name = "Ngoc"
password = "123"
def login():
if nameInput.get() == name:
print "Successfully"
button... |
c642156dc16d9673ff5b1da0c8432711333c508f | theTijesuni/Simple-Stock-Calculator | /simple_stock_calculator.py | 1,069 | 3.953125 | 4 | #features coming soon
# go back
# quit
# add GUI
def stock_diff():
print("a. Calculate price difference")
print("b. Increase by x percent\n")
user_input = input("A or B:\n>..")
while (user_input != "q"):
if (user_input.lower() == "a" ):
print("Press to \"go back\"\n")
... |
f1462bc609066c7ec29481e1a299798e59a5887a | djtorel/python-crash-course | /Chapter 08/Try It/Try07/album.py | 1,158 | 4.71875 | 5 | # Write a function called make_album() that builds a dictionary
# describing a music album. The function should take in an artist name
# and an album title, and it should return a dictionary containing these
# two pieces of information. Use the function to make three dictionaries
# representing different albums. Pr... |
d97d7c1be02b1cc8c921f6f68e45685160426bd9 | tanasin-vivitvorn/platformx | /fullstack/test3.py | 2,465 | 3.6875 | 4 | import unittest
import math
#from memory_profiler import profile
class Node:
def __init__(self, value):
self.value = value
self.parent = None
#@profile
def setup():
nodes = [11]
for i in range(1, 10):
nodes.append(Node(i))
parent_value = int(math.floor(i/2))
if p... |
71d28d3efd2adc3003610b9ef5243e18b2fc9e71 | turing4ever/codesnippets | /leetcode/1.two-sum.python3.py | 376 | 3.53125 | 4 | class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
diff = {}
for i in range(len(nums)):
if (target - nums[i]) in diff:
return [diff[target-nums[i]], i]
elif ... |
e649cf77c3e51527e4dd863f3b80e1fe7fb180d7 | kopair/code-python | /day-01-20190714/investment.py | 314 | 3.953125 | 4 | # -*- coding: utf-8 -*-
amount = float(input('Enter a amount:'))
inrate = float(input('Enter a inrate:'))
period = int(input('Enter a period:'))
value = 0
year = 1
while year <=period:
value = amount + (amount * inrate)
print('every year {} rate {:.2f}'.format(year,value))
amount = value
year += 1 |
599a567eda2ab3dd22281a709dc093515a4e4975 | YuriiKhomych/ITEA_course | /DarinaLeliuk/4_iterations/2.py | 211 | 3.5625 | 4 | series=[2, 3, 4, 5, 7, 11, 22]
counteven=0
countodd=0
for myelement in series:
if myelement % 2 != 0:
counteven += 1
elif myelement % 2 == 0:
countodd +=1
print(countodd)
print(counteven) |
2326b1b2192c04af5b35126f7e8a24b1c9392faf | okanbskn/ALP2-Uebungen | /U1/A1.py | 110 | 3.515625 | 4 | def sum(a):
res = 0
for n in a:
res += n
return res
print sum([11,11])
print sum([1,2,3,4,5,6,7,8,9,10]) |
93d7ba45ab2c5fae3e234d8f3afb8c67bbde7ebc | schehat/python_snippets | /default_parameters.py | 511 | 4.03125 | 4 | def append_number_wrong(num, numbers=[]):
numbers.append(num)
print(num)
print(numbers)
# behaves not like expected due to mutable parameteter
# the function share the same list
print("wrong:")
append_number_wrong(1)
append_number_wrong(2)
# always use immutable data structure
def append_n... |
dc97b214cbb5eda911b0d907710ce8cc167dfdcc | Lee-3-8/CodingTest-Study | /level2/압축/정한.py | 1,126 | 3.5625 | 4 | # 2018 KAKAO BLIND RECRUITMENT [3차] 압축
# chr, ord 을 이용해 아스키 코드 이용
# 뇌절 파티한 문제 (꼭 다시 풀자)
def solution(msg):
answer = []
indexing = dict()
idx = 26
max_len = 1
for i in range(0, idx):
indexing[i + 1] = f"{chr(ord('A')+i)}"
i = 0
while i < len(msg):
attach = ""
f... |
808bd73ed737ca5120b19ec47390c5768d8961fd | mrnglory/Programming-Linguistics | /1. Python/PL_SOL_04.py | 965 | 3.859375 | 4 | class Node:
def __init__(self,data):
self.left = None
self.right = None
self.data = data
class Tree:
def Preorder(self, root):
if root:
print(root.data)
self.Preorder(root.left)
self.Preorder(root.right)
def Inorder(self, root)... |
e0971fccc41eab35412f7c71c9b90f24e23a258d | wulinlw/leetcode_cn | /leetcode-vscode/147.对链表进行插入排序.py | 2,564 | 3.921875 | 4 | #
# @lc app=leetcode.cn id=147 lang=python3
#
# [147] 对链表进行插入排序
#
# https://leetcode-cn.com/problems/insertion-sort-list/description/
#
# algorithms
# Medium (63.00%)
# Likes: 136
# Dislikes: 0
# Total Accepted: 22.6K
# Total Submissions: 35.7K
# Testcase Example: '[4,2,1,3]'
#
# 对链表进行插入排序。
#
#
# 插入排序的动画演示如上。从... |
1ec11351a0fb272855ff4b0d7283916fb70c87de | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/prtnic017/mymath.py | 347 | 3.828125 | 4 | # Student Number: PRTNIC017
# Date: 4/13/14
def get_integer(message):
n = input("Enter " + message + ":\n")
while not n.isdigit():
n = input("Enter " + message + ":\n")
return eval(n)
def calc_factorial(value):
factorial = 1
for i in range(1, value + 1):
factorial... |
7a7930b1e6c93caca2b4b4019aae559bd4cbeca7 | MBagdal/Linguagem_Programacao | /Python/Marco/Registro com SQLite - Procedural/Exemplo1.py | 2,931 | 3.6875 | 4 | import sqlite3
import time
tipo_ingresso = {'Vip': 70, 'Normal': 50,'Estudante': 25};
connection = sqlite3.connect('ExemplosPython.db')
cursor = connection.cursor()
def CreateTable():
cursor.execute('CREATE TABLE IF NOT EXISTS Clientes (id integer, nome_cliente text, tipo_ingresso text, valor_ingresso real, data_co... |
574d04a55201422a5386851eb21679531e775afd | Ayaz-75/Black_jack-Guessing_number-highest_bid-nested_dict | /grading_program_using_dictionary.py | 492 | 3.671875 | 4 | student_score = {
"ayaz": 81,
"wassi": 78,
"Muzi": 99,
"zahoor": 74,
"asifil": 62
}
student_grades = {}
for student in student_score:
score = student_score[student]
if score >= 90:
student_grades[student] = "Outstanding"
elif score > 80:
student_grades[student] = "Exce... |
717a9b4c4ac6718b4e596128e1aaca2b6d04d715 | Descent098/PYTH-101 | /7. Extras/challenge.py | 499 | 3.953125 | 4 | """
=========== Challenge 1 =============
Below is a game in which you specify
how many cookies there are at the beginning.
on each 'turn' a random amount between 1-10
of cookies are removed. Once there are no cookies
use an f-string to print if player 1 (an even number
of turns) or player ... |
b6fc237f6996114eda218578d778a114aaeaa1c9 | Luolingwei/LeetCode | /Heap/Q703_Kth Largest Element in a Stream.py | 556 | 3.625 | 4 | from heapq import *
class KthLargest:
def __init__(self, k: int, nums):
heapify(nums)
self.large,self.small=nums,[]
self.k=k
def add(self, val: int):
heappush(self.small,-heappushpop(self.large,val))
while len(self.large)>self.k-1:
heappush(self.small,-heapp... |
5257a95f81e1a2808fc39c039c9f2779d8189981 | GSvensk/OpenKattis | /LowDifficulty/busnumbers.py | 766 | 3.71875 | 4 | def make_chain(bus_lines, total_buses, counter):
print(bus_lines[counter], end="")
while counter+2 < total_buses:
if (bus_lines[counter+1] == bus_lines[counter]+1) & (bus_lines[counter+2] == bus_lines[counter]+2):
counter += 1
else:
break
print("-" + str(bus_lines[co... |
f1a7f3efefb242121d327e558919a8d1b3882921 | tang1323/Ing_Interview | /tools/interview-two.py | 5,925 | 4 | 4 |
# 41、举例说明异常模块中try except else finally的相关意义
# try..except..else没有捕获到异常,执行else语句
# try..except..finally不管是否捕获到异常,都执行finally语句
# try:
# num = 100
# print(num)
# except NameError as errorMsg:
# print('产生错误了 :%s' % errorMsg)
# else:
# print('没有捕获到异常,则执行这个语句')
#
#
# try:
# num = 100
# print(num)
#... |
1d987a61e179ea7b51385d1ce4afdf2c0dcf142d | saravey2021/homework-week-11 | /Homework week 11/thur1.py | 394 | 4.25 | 4 | def sumFromTo(startValue,endValue):
sum = 0
for i in range(startValue , endValue+1):
if endValue > startValue:
sum = sum + i
else:
sum = sum + 0
return sum
startValue=int(input("Start Value:"))
endValue=int(input("End Value:"))
print("The sum of number between"+str(... |
573f10f82adc17f902e1af2d5c628d1897cc0565 | bimri/learning-python | /chapter_34/raise-exceptions.py | 1,725 | 4.3125 | 4 | "Raising Exceptions"
'''
the following two forms are equivalent—both raise an instance of the exception class named,
but the first creates the instance implicitly:
'''
raise IndexError # Class (instance created)
raise IndexError() # Instance (created in statement)
'''
We can also create ... |
f76f2bf4ad107332e6bc9e134b42f88fb2c02ab4 | kevokvr/PythonPractice | /Assignment3/Assignment3.py | 2,993 | 4.40625 | 4 | import unittest
'''
Write a recursive method that takes 1) a string to find, 2) a string to replace the found string with, and 3) an initial
string. Return the initial string with all the found strings replaced with the replacement string. You may not use loops
or the built-in string methods except comparison, length... |
1eca59a003b42e6f286acd2eac74d6be07592bba | ruzguz/python-stuff | /7-loops/numbers.py | 785 | 4.3125 | 4 | import random
def run():
number_found = False
# generating random range from user input
min = int(input('Introduce the min value: '))
max = int(input('Introduce the max value: '))
while max <= min:
max = int(input('max value have to be greater than min value: '))
random_number = r... |
b2ea5410416669ddf83d801789bf4c4d19ece798 | acmduzhuo/python | /Python_homework_2019-11-15/第六章/课后习题/6.2.py | 1,094 | 3.921875 | 4 | class Vecter3:
def __init__(self, x=0, y=0, z=0):
self.X = x
self.Y = y
self.Z = z
def __add__(self, n):
r = Vecter3()
r.X = self.X + n.X
r.Y = self.Y + n.Y
r.Z = self.Z + n.Z
return r
def __sub__(self, n):
r = Vecter3()
r.X = s... |
31879e7f1edfb15544d3274e0c20bf0f02366d48 | AnatoliyChabanenko/lesson2 | /lesson6_2.py | 198 | 3.65625 | 4 | #первая
v= [1 , 2, 3, 4,5,1 ,3 ,5, 7 ,7]
k=[]
for i in range (len(v)):
k.append(i)
dicor = dict(zip(v, k))
print(dicor)
# последняя
#d = {a: a ** 2 for a in range(1,11)}
#print(d) |
4e980d0e51b15fcfc69e71ebb8e53e10b474a1ca | iceljc/Green-Taxi-NYC-Analysis | /code/question1.py | 959 | 3.71875 | 4 | """
This code solves for Question 1
"""
import pandas as pd
import numpy as np
import urllib.request
import os, ssl
# fix the error when using urllib.request.urlretrieve
if (not os.environ.get('PYTHONHTTPSVERIFY', '') and
getattr(ssl, '_create_unverified_context', None)):
ssl._create_default_https_context ... |
f2056ff46ce6e38c3b6ca553bbdec7f59d60b198 | vtsartas/ejpython | /ejpy/ejElenaPY/28_hoja-VI-5_nota-ponderada-60-40.py | 716 | 3.953125 | 4 | # Ejercicio 28 - Hoja VI (5) - Indicar la nota ponderada según el criterio dado
# (parte teórica 60%, práctica 40%) de cada uno de un número determinado de alumnos
numalumnos=int(input("Introduce el número total de alumnos:\n"))
print("Usa el punto '.' para los decimales")
for contador in range(1,numalumnos+1):
... |
b1a1d4dc8c091c5263b7daa270c1019fc7775bfd | alejo8591/dmk-django | /lab2/lab2_8.py | 402 | 3.671875 | 4 | # -*- coding: utf-8 -*-
class A(object):
def __init_(self):
print("A")
super(A, self).__init__()
class B(A):
def __init__(self):
print("B")
super(B, self).__init__()
class C(A):
def __init__(self):
print("C")
super(C, self).__init__()
class D(C, B):
def __init__(self):
print("D")
super(D, self).... |
9725311d82d1ad171b26f12fa0fa5b3377a628a7 | yuweichen1008/leetcode-1 | /222_CountComplete/222_CountComplete2.py | 610 | 3.546875 | 4 | class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return 0
node=root
depth=0
while node:
node=node.left
depth+=1
num=(1<<depth-1) -1
level=depth-2
w... |
23ac644229e19ab1d030a2da559641cf53d263fc | morluna/Elements-of-Software-Design | /Assignment 1/Bowling.py | 3,038 | 3.71875 | 4 | # File: Bowling.py
# Description: Program that reads a file with bowling scores and prints a scoreboard for each game
# Student's Name: Marcos J. Ortiz
# Student's UT EID: mjo579
# Course Name: CS 313E
# Unique Number: 51320
#
# Date Created: September 4, 2016
# Date Last Modified: September 8, 2016
def isst... |
85522c222a63b8236b0af9e93404e384e89acb3a | voodoopeople42/Vproject | /phonebook1.py | 2,400 | 4.03125 | 4 | contacts = (
{"Имя": "Игорь", "Номер": "094-456-72-89"},
{"Имя": "Виктор", "Номер": "092-664-52-88"},
{"Имя": "Сергей", "Номер": "089-435-23-23"},
)
FORMAT_STR = '{:<15} {:>12}'
def list(contacts):
print(FORMAT_STR.format("Имя", "Номер"))
for contact in contacts:
print(FORMAT_STR.format(
contact ("Имя"),
... |
cd854b7b0f06008e0b78456083efd9f828436254 | eduardodcs/python-basico | /01comissao.py | 363 | 3.75 | 4 | print("Cálculo de salário com comissão (6%)")
salarioFixo = float(input("Digite o salário do vendedor: "))
vendas = float(input("Digite o total vendido no mês: "))
vComissao = vendas * 0.06
salarioMes = salarioFixo + vComissao
print("O vendedor receberá {:.2f} de salário mais {:.2f} de comissão. Total {:.2f}".format(sa... |
9957e509bf209b52e7e34de8b4ceed7cf997f858 | ThoPhD/InterviewTests | /super.py | 1,074 | 4 | 4 | class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * self.length + 2 * self.width
def what_am_i(self):
return 'Rectangle'
class Square(Recta... |
5ab8e34ed5ad974ecfb36c851ac0a1df38555260 | Platforuma/Beginner-s_Python_Codes | /10_Functions/17_Function--Lambda-operators.py | 478 | 4.21875 | 4 | '''
Create lambda functions for add, sub, mult and div
'''
add = lambda num1, num2: num1 + num2
dif = lambda num1, num2: num1 - num2
mul = lambda num1, num2: num1 * num2
div = lambda num1, num2: num1 / num2
print("Sum :", add(9,3))
print("Difference :", dif(9,3))
print("Product :", mul(9,3))
print("Division... |
4920eee4c800f21553385e4fe64490ee4cae3cbf | munniomer/StackOverflow-API | /app/validators/validators.py | 1,009 | 3.578125 | 4 | """Validators Module"""
import re
from app.api.v1.models.users_model import users
class Validators():
"""Validators Class"""
def check_email(self, email):
"""Method for checking if user email exist"""
user = [user for user in users if user['email'] == email]
if user:
retur... |
6e1f9570281f331621c56e6720a65f61fae7c772 | gdh756462786/Leetcode_by_python | /Array/Shuffle an Array.py | 1,360 | 4.375 | 4 | # coding: utf-8
'''
Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must
equally likely to be returned.
solution.shuffle();
// Rese... |
5b3ce34d4f5aefc21f37e186e6121ab95e2b521a | dez-gm/practica-fundamentos-python | /segundapractica.py | 633 | 4.125 | 4 | # Imprimir tu nombre
# cadena de caracteres
# nombre = input("Introduce tu nombre: ")
# print(f"Hola {nombre}")
# entero
edad = 25
# flotante - decimales
altura = 1.75
# convertir a flotante
edadString = str(edad)
print(edad + edad)
print(edadString + edadString)
print(type(edad))
tuEdad = input("Intorduce tu edad... |
66ba13c1a092d5389c8e576f096fb3fddb6f152e | Marcelo8173/phyton-fundamentos | /lacoDeRepeticao.py | 441 | 4.25 | 4 | for n1 in range(1,6):
print(n1)
# colocando um step
for n2 in range(5,0,-1):
print(n2)
# for com soma
print("\nSoma")
soma = 0
for n3 in range(0,6):
soma = soma + n3
print(soma)
# string
print("\nString")
palavra = "marcelo"
for letra in palavra:
print(letra)
# while
print("\nWhile")
numero = 1
whil... |
f0bdbc292ed1150d28cebed0bc1cc39eb5485bc2 | ZhuJiahui/Text-Categorizer | /textcat.py | 8,846 | 3.734375 | 4 | #Text Categorization Program for NLP
#Ramon Sandoval
import re, os, string, math, operator
trainListName = raw_input("Please enter training data list name: ")
testListName = raw_input("Please enter testing data list name: ")
resultName = raw_input("Please enter output file: ")
#Default files if nothing is e... |
4b3f541e0fb7577e479e9dcab57ef1cca242636b | gupongelupe/ExerciciosFeitosPython | /ex057.py | 276 | 4.03125 | 4 | sexo = str(input('Digite seu sexo: [M/F] ')).upper()
while sexo != 'M' and sexo!= 'F':
sexo = str(input('Por favor digite novamente [M/F] ')).upper()
if sexo == 'M':
print('És macho my amigo!')
elif sexo == 'F':
print('És Moça my manita!') |
225fc7da43f46e59685b9b88e9452a2407c58163 | thinkreed/lc.py | /algo/first/p287_find_the_duplicate_number.py | 502 | 3.53125 | 4 | class Solution:
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
start = 1
end = len(nums) - 1
while start < end:
middle = start + (end - start) // 2
count = 0
for num in nums:
if n... |
229628f40af614034e0eb9d04181f1f86d6ebe3f | w51w/python | /0914_자료구조/중첩리스트.py | 216 | 3.984375 | 4 | a=['a','b','c']
n=[1,2,3]
x=[a,n]
print(x)
print(x[0])
print(x[0][1])
list2d= [[3,1,2],[1,5,2,6,3,8]]
print(list2d)
list2d[1].sort();
print(list2d)
list2d[0].sort();
print(list2d)
list2d[1].reverse();
print(list2d); |
9ba9402b5e4cbeaaa0d125fc0b1d5a90bee4e868 | ataias/Online-Judge-Submissions | /uri/1113.py | 292 | 3.78125 | 4 | #!/usr/bin/env python3
def main():
X, Y = 0, 1
while X != Y:
X, Y = [int(x) for x in input().split()]
if X == Y:
break;
if X > Y:
print("Decrescente")
else:
print("Crescente")
if __name__ == '__main__':
main()
|
bc0f9b830d3d7f98ed2ebffa2923af8cf10f7e0b | NikolasMoatsos/Algo-Assignments | /count_fixed_polyominoes.py | 2,501 | 3.625 | 4 | import sys,pprint
# The class with the "different polyomino" counter.
class Counter:
def __init__(self):
self.count = 0
# Methods for add and return.
def AddOne(self):
self.count += 1
def ValueOf(self):
return self.count
# This checks if "i" is a neighbor of the par... |
fafa73aff5cfc4b1974d3ea83c367ba0edbad403 | Ryuya1995/leetcode | /q58_Length_of_Last_Word.py | 424 | 3.625 | 4 | class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
s = s.split()
return len(s[-1])
def lengthOfLastWord1(self, s):
length = 0
tail = len(s) - 1
while tail >= 0 and s[tail] == ' ':
tail -= 1
... |
41e9e67fc7477020d0842243e3c7ae0c71e764fe | matheusbernat/GitRep | /Tentor/tenta2015_1.py | 3,786 | 3.625 | 4 | ################################################
# TENTA 2015, 1
################################################
# FACIT P UPPGIFTERNA JAG INTE LSTE:
# Uppgift 4 (komma p vettiga namn, return lista med alla mjliga namn
def combos_facit(word):
n = len(word)
res = []
for left in range(1, n-2+1):
f... |
a8fd983b8ecc87f5faf968883647b3fb1336dbd0 | tspolli/exercises | /temometro.py | 424 | 4.21875 | 4 | '''
Faça um Programa que peça a temperatura em graus Farenheit,
transforme e mostre a temperatura em graus Celsius.
C = (5 * (F-32) / 9).
'''
print("** CALCULO DE FARENHEIT PARA CELSIUS **")
print("Informe a temperatura em graus Farenheit: ")
graus_farenheit = int(input())
graus_celsius = 5*(graus_farenheit-32)/9
pri... |
48edcc4cb67720366140929875c616baffee0ffb | Illugi317/gagnaskipan | /stack_queue/stack.py | 930 | 3.703125 | 4 | class Stack:
def __init__(self):
self.size = 0
self.capacity = 4
self.array = [0] * self.capacity
def __str__(self):
ret_str = ""
for x in range(self.size):
ret_str += f"{self.array[x]}, "
return ret_str[:2]
def push(self, value):
if ... |
6ce3ccfb1b09f3ab59c8d830f1cbc2ca06c9dd59 | RGingrich8/StandManager | /MainMenu.py | 958 | 3.921875 | 4 | class MainMenu:
def __init__(self, day_number): #Constructor
self.day_number = day_number
self.options = ["A - Advance to Day", "B - Buy Supplies", "S - Set Recipe and Prices", "V - View Career", "Q - Quit Game"]
self.commands = ["B", "S", "V", "A", "Q"]
def menu(self): #Run t... |
15f1085e70a20755be027a0bba5ffa914b6dcc2c | David-Xiang/Online-Judge-Solutions | /210731/LC13.py | 704 | 3.546875 | 4 | # LeetCode 13
# Roman to Integer
# Number
from typing import List
class Solution:
cToInt = dict(I=1, V=5, X=10, L=50, C=100, D=500, M=1000)
def romanToInt(self, s: str) -> int:
ans = 0
for i in range(len(s) - 1):
val = self.cToInt[s[i]]
if s[i:i+2] in ("IV", "IX", ... |
767b41712c5d706b24c60c67b5ad69b45878ef4d | kamouzougan/firstProgram | /menu_total.py | 893 | 4 | 4 |
import time
def main() :
moreitem=True
total = 0
while(moreitem):
time.sleep(3)
print ('Welcome to the StemBrain')
print ("Please enter y for yes amd n for no ")
response = input()
if response == 'y' or response =='Y':
print("please enter for item na... |
058b7b6b2ee2e3502d3dc2159e600c9da4074a1e | Alexandra2802/sudoku | /solver.py | 2,137 | 3.578125 | 4 | board = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
def print_board(bo):
for i in range(len(bo)):
if i%3==0 a... |
c5ebc8d79d05eb14b86d878cc6254bb62f2e61c3 | CircularWorld/Python_exercise | /month_02/teacher/day15/thread_lock.py | 439 | 3.921875 | 4 | """
线程同步互斥 Lock方法
"""
from threading import Thread,Lock
lock = Lock() # 创建锁
# 共享资源
a = b = 0
def value():
while True:
lock.acquire() # 上锁
if a != b:
print("a = %d,b = %d"%(a,b))
lock.release() # 解锁
t = Thread(target=value)
t.start()
while True:
with lock: # 上锁
... |
1c8341a9229070e89fcafa63bef2e6d314db0675 | Cubba2412/StudentGrades | /loadGrades.py | 25,217 | 3.984375 | 4 | import pandas as pd
from userInput import *
import os.path
import numpy as np
#Suppress pandas warnings from user
pd.set_option('mode.chained_assignment', None)
def loadGrades():
# loadGrades Loads in a CSV file containing N x M data values and
# returns it as pandas dataframe
##
# Usage: gr... |
57fdd81e449737ce881b563705ff71abc670cd03 | hashkanna/codeforces | /epi/linked_list/list.py | 731 | 3.875 | 4 | class ListNode:
def __init__(self, data=0, next=None):
self.data = data
self.next = next
def search_list(L, key):
while L and L.data!=key:
L = L.next
return L
def insert_after(node, new_node):
new_node.next = node.next
node.next = new_node
d... |
3d0360601225f8a1bed5b5213433900b4f9f2f42 | dongxiexiyin/leetcode | /015-3sum/3sum.py | 1,520 | 3.5625 | 4 | # Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
#
# Note:
#
# The solution set must not contain duplicate triplets.
#
# Example:
#
#
# Given array nums = [-1, 0, 1, 2, -1, -4],
#
# A solution set is:... |
8567a5a5ea606c8e24363ff22fda8ce470c50bc0 | wkdghdwns199/Python_basic_and_study | /chap_5/14_lam_bda.py | 279 | 3.8125 | 4 | # 함수를 선언합니다.
power=lambda x:x*x
under_3= lambda x: x<3
#변수를 선언합니다.
list_input_a=[1,2,3,4,5]
#map() 함수를 사용 합니다.
output_a = map(power,list_input_a)
print(list(output_a))
output_a=filter(under_3,list_input_a)
print(list(output_a)) |
503b34b431b1c99a45c0e576ad27dc00a086d24f | diegofregolente/30-Days-Of-Python | /11_Day_Functions/3.py | 238 | 4.09375 | 4 | def add_all_nums(*nums):
tot = 0
for n in nums:
if isinstance(n, int): # or use type(n) to verify
tot += n
else:
print(f'{n} is not a number')
return tot
print(add_all_nums(2, 'b', 3))
|
816ef08876a7b8726439112325a4c8f5053ba516 | oswalgarima/leetcode-daily | /stack/baseball_game.py | 1,734 | 3.5625 | 4 | """
682. Baseball Game
https://leetcode.com/problems/baseball-game/
You are keeping score for a baseball game with strange rules.
The game consists of several rounds, where the scores of past rounds may affect future rounds' scores.
At the beginning of the game, you start with an empty record.
You are given a list of... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.