blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
ffb710c2c13f9fb8b6fdc5c07b14cf04492051f5 | jamiezeminzhang/Leetcode_Python | /hash/347_O_Top_K_Frequent_Elements.py | 757 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 02 20:39:52 2016
347. Top K Frequent Elements
Total Accepted: 1132 Total Submissions: 2536 Difficulty: Medium
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].
Note:
You may assume k is ... |
1116f837dee72cb865044c120f6f95fbe56e8c75 | jamiezeminzhang/Leetcode_Python | /ALL_SOLUTIONS/127_OO_Word_Ladder.py | 1,966 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 4 21:45:27 2016
127. Word Ladder My Submissions Question
Total Accepted: 66019 Total Submissions: 337427 Difficulty: Medium
Given two words (beginWord and endWord), and a dictionary's word list, find
the length of shortest transformation sequence from beginWord to endWo... |
2836f7639ad2855cedc48cac08000e57bbc2334d | jamiezeminzhang/Leetcode_Python | /math/372_OO_Super_Pow.py | 674 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thursday July 14 07:07:11 2016
372. Super Pow
Total Accepted: 2171
Total Submissions: 7216
Difficulty: Medium
Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.
Example1:
a = 2
b = ... |
e65ea45ba9f0a13ac635b3e27b0c7b5e5cd301f5 | jamiezeminzhang/Leetcode_Python | /ALL_SOLUTIONS/114_OO_Flatten_Binary_Tree_to_Linked_List.py | 1,472 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 3 04:07:11 2016
114. Flatten Binary Tree to Linked List My Submissions Question
Total Accepted: 72882 Total Submissions: 240709 Difficulty: Medium
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ ... |
ed15b8334573674a18af1cb9f32eff9b42948785 | jamiezeminzhang/Leetcode_Python | /string/012_integer_to_roman.py | 1,995 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 22 13:44:48 2015
LeetCode #12 Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
@author: zzhang
"""
"""
Better solution
class Solution:
# @return a string
def intToRoman(self, num):
... |
aef7109e486d58cf46e529ceae1bc8e5220aeacd | jamiezeminzhang/Leetcode_Python | /sorting_and_search/275_O_H_Index_II.py | 1,038 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 21 16:03:29 2016
275. H-Index II
Total Accepted: 18322 Total Submissions: 56764 Difficulty: Medium
Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?
Hint:
Expected runtime complexity is in O(log n) and... |
719301c5138ac2c65f1fff5589aa896765e08c2c | jamiezeminzhang/Leetcode_Python | /ALL_SOLUTIONS/342_Power_of_Four.py | 754 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 19 16:17:13 2016
342. Power of Four
Total Accepted: 3328 Total Submissions: 9711 Difficulty: Easy
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Cou... |
5ef32bfe37d2ae96cfed781851aac66b74126810 | jamiezeminzhang/Leetcode_Python | /ALL_SOLUTIONS/200_Number_of_Islands.py | 2,175 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 15 07:53:24 2016
200. Number of Islands
Total Accepted: 35558 Total Submissions: 133900 Difficulty: Medium
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands hori... |
f548840ac46606629fcb5a50d06eb833eeaa05f8 | jamiezeminzhang/Leetcode_Python | /ALL_SOLUTIONS/110_Balanced_Binary_Tree.py | 1,070 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 3 01:25:01 2016
110. Balanced Binary Tree My Submissions Question
Total Accepted: 94528 Total Submissions: 283797 Difficulty: Easy
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
wh... |
5cc3efadd1d57cc71815f4e2a55c0ec21ec11f31 | jamiezeminzhang/Leetcode_Python | /ALL_SOLUTIONS/119_Pascals_Triangle_II.py | 963 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 3 22:13:07 2016
119. Pascal's Triangle II My Submissions Question
Total Accepted: 65337 Total Submissions: 208879 Difficulty: Easy
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1].
Note:
Could you optimize your a... |
74b56b870bf7ad86da4628de3abbe64cc77655e9 | jamiezeminzhang/Leetcode_Python | /ALL_SOLUTIONS/131_O_Palindrome_Partitioning.py | 1,063 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 5 08:12:26 2016
131. Palindrome Partitioning My Submissions Question
Total Accepted: 58009 Total Submissions: 211642 Difficulty: Medium
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning... |
7af2826b11f0f6fd907d17cb33a39c1384c13c57 | jamiezeminzhang/Leetcode_Python | /ALL_SOLUTIONS/035_search_insert_position.py | 870 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 04 13:08:49 2015
LeetCode # 35: Search Insert Position
Given a sorted array and a target value, return the index if the target is
found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few ex... |
3a2b4d34514088ea435221a5686db329bf3a6f69 | jamiezeminzhang/Leetcode_Python | /ALL_SOLUTIONS/283_Move_Zeros.py | 949 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 22 14:16:35 2016
283. Move Zeroes
Total Accepted: 57202 Total Submissions: 131765 Difficulty: Easy
Given an array nums, write a function to move all 0's to the end of it while maintaining the
relative order of the non-zero elements.
For example, given nums = [0, 1, 0,... |
7504557102ef1f9e630da78b17d724ef66d0c9be | jamiezeminzhang/Leetcode_Python | /ALL_SOLUTIONS/066_plus_one.py | 739 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 27 03:38:04 2016
66. Plus One
Total Accepted: 104513 Total Submissions: 305610 Difficulty: Easy
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.... |
f791001ef212e94de7adbf9df8df4812bc198622 | jamiezeminzhang/Leetcode_Python | /others/073_Set_Matrix_Zeroes.py | 1,863 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 28 10:55:49 2016
73. Set Matrix Zeroes
Total Accepted: 69165 Total Submissions: 204537 Difficulty: Medium
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
click to show follow up.
Follow up:
Did you use extra space?
A strai... |
80d90549aaa7dfe5dbcf355e5fef0caf6ff6b9bf | sandipan94/FIND-AVERAGE-OF-A-STUDENT-S-MARKS-IN-A-MARKSHEET | /source.py | 477 | 3.546875 | 4 | if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
query_name_score = list(student_marks[query_name])
phy = query_name_score[0]
... |
2eb1bbef82199d0c2f35fce4c3a99d5ab68b6591 | Nurckye/HMAC-compute | /HMAC.py | 2,186 | 3.5 | 4 | #!/usr/bin/env python3
# Author: Radu Nitescu
# Date: 26 November 2019
# Description: computes HMAC message authentication code
import hashlib
import string
import random
IPAD = 0x36 #54
OPAD = 0x5C #92
def generate_pseudo_random_key(message):
return ''.join(random.choices(string.ascii_uppercase +
... |
a15105eea6cf6a6d534d80c3396e81f2b04ebf9f | MehCheniti/Python | /IN1000/Trix 11/plante.py | 882 | 3.75 | 4 | class Plante:
def __init__(self, vannbeholder, maksgrenseVann):
self._vannbeholder = vannbeholder
self._maksgrenseVann = maksgrenseVann
def vannPlante(self, vannCl):
self._vannbeholder += vannCl
if self._vannbeholder > self._maksgrenseVann:
return False
def nyDa... |
7ab9fedb0729c59305275eefc01f832d562a7ce5 | MehCheniti/Python | /IN1000/Trix 3/raad.py | 158 | 3.78125 | 4 | saldo = float(input("Saldo? "))
totalpris = float(input("Totalpris? "))
if saldo >= totalpris:
print("Du har råd.")
else:
print("Du har ikke råd.")
|
abf8ce7a6463af84ba8822cef48b21625e23693b | MehCheniti/Python | /IN1000/Trix 2/tekstutskrift_med_formattering.py | 153 | 3.546875 | 4 | list1 = {"Navn 1" : "Arne", "Navn 2" : "Dag", "Navn 3" : "Ellen"}
for name1, name2 in list1.items():
print("{0:10} : {1:10s}" .format(name1, name2))
|
89967b420e507960972a0379b3d350712905b3a7 | MehCheniti/Python | /IN4050/Assignment 1/dist.py | 13,934 | 3.625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import math
import statistics
#import csv file
import csv
with open("european_cities.csv","r") as f:data=list(csv.reader(f, delimiter=';'))
cities=data[0]
distances=data[1:]
import itertools
import time
begin = time.time()
def distance_sta... |
855432d0723102559847da3357a4d70445f89939 | MehCheniti/Python | /IN1000/Obligatorisk innlevering 5/repetisjon1.py | 1,025 | 3.75 | 4 | # Dette programmet ber brukeren om å taste inn tekststrenger og skriver da ut
# en sammenslått versjon av tekstrengene.
mineOrd = []
def slaaSammen(streng1, streng2):
return str(streng1) + str(streng2)
def skrivUt(liste):
for i in liste:
print("De sammenslåtte tekststrengene er ", i, ".", sep="")
#H... |
c137deb94a8d2771cf648b7bf46ee2c9f4f9fef5 | MehCheniti/Python | /IN1000/Trix 3/feil_som_ikke_gir_feilmelding.py | 139 | 3.578125 | 4 | x = 0
y = 0
x = int(input("Tast inn et heltall: "))
y = int(input("Tast inn et heltall til: "))
print("Summen av tallene er:", int(x+y))
|
ce02faa86026e4042fe9609c39c3280522aa1e87 | bunty247/cloud-computing-assignment-1 | /dbFile/dbScript.py | 740 | 3.640625 | 4 | import sqlite3
conn = sqlite3.connect('cloud_assign.db')
cur = conn.cursor()
# cur.execute("""DROP TABLE IF EXISTS user_data""")
# cur.execute("""CREATE TABLE user_data
# (username text, password text, first_name text, last_name text, email_id text)""")
# cur.execute("""DROP TABLE IF EXISTS user_file""")
#... |
e401d845941204f20bee8943a1dc82ca0ddf650f | pompieru/myguidedojo | /fibonacci.py | 185 | 3.796875 | 4 | n = int(input("enter how many numbers you want in this series"))
first = 0
second = 1
for i in range (n) :
print(first)
temp = first
first = second
second = temp+second
|
4ac71bf73590e94fa151963d986ff4d6a347144b | Dominyka20/homework_repository | /question2.py | 324 | 3.953125 | 4 | # 2. Даны действительные числа x и y.
# Получить (|x|-|y|)/(1+|xy|)
x = int(input("Введите первое число:"))
y = int(input("Введите первое число:"))
question = (abs(int(x)) - abs(int(y))/(1 + abs(int(x)*int(y))))
print("Ответ:" + " " + str(question))
|
dc6600d867353c9d870c077237274174163327bd | Panlak/lab-1 | /Desktop/lab vstup/ммааммаа.py | 162 | 3.75 | 4 | dup = 'mama'
dup1 = str()
for char in dup:
a = int(0)
if char == chr(32):
dup1 += char
else:
dup1 += char + char
print(dup1) |
6b89bfb47b3a25fa8190ff066318a94ef06b0b25 | douglasrusse11/rps_weekend_homework_03 | /models/game.py | 1,140 | 3.609375 | 4 | from models.player import Player
from random import choice
class Game:
def __init__(self, player1, player2=None):
self.player1 = player1
self.player2 = player2
self.HANDS = {"rock": 0, "paper": 1, "scissors": 2}
def play(self):
if self.invalid_hand():
return 404
... |
beeee11bc08c320e6e721c4d0b415b445461fdec | antwal/buraco | /specs/buraco_spec.py | 1,885 | 3.5 | 4 | #coding:utf-8
import unittest
from should_dsl import *
from player import *
from card import Card
from buraco import *
class BuracoSpec(unittest.TestCase):
def setUp(self):
self.hugo = Player("Hugo")
self.pedro = Player("Pedro")
self.players = [self.hugo, self.pedro]
self.buraco ... |
ca943baeed5005c856a02e003f48b31152be9936 | antwal/buraco | /specs/card_spec.py | 274 | 3.59375 | 4 | import unittest
from should_dsl import *
from card import Card
class CardSpec(unittest.TestCase):
def it_should_have_a_value_and_a_suit(self):
card = Card('J', 'spades')
card.value |should| equal_to('J')
card.suit |should| equal_to('spades')
|
df69cafa4aa4527e4180d7e197b72dba2c347a35 | ib7872/1Day1Coding_B | /20210417/성빈질문1.py | 232 | 3.96875 | 4 | numbers = [1,2,3,4,5,6,7,8,9]
output = [[],[],[]]
for number in numbers:
output[(number%3)-1].append((number))
print(output)
# print(output[0])
# print(output[1])
# print(output[2])
# print(output[3])
# print(output[4])
|
3cf7f0e66b8c81c56c8b362fc05f000c243e9249 | HimNG/CrackingTheCodeInterview | /2.2/2.2/_2.2.py | 1,480 | 4.15625 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class linkedlist :
#count=0
def __init__(self):
self.head=None
def insert_at_begin(self,data):
node=Node(data)
node.next=self.head
self.head=node
# kth last element with rec... |
91b8efcba2052d32af2579a1a77956fe86673592 | ZhuravelViktoria/ZhuravelViktoria-Lab3 | /3.py | 837 | 3.75 | 4 | print("Програма порахує кількість рядків які завершуються заданим символом")
print("Файл повинен розташовуватися в папці з програмою та називатися line.txt")
print("Файл не повинен містити порожніх рядків")
print("Текст повинен бути написаний латиницею")
f = open('line.txt')
line = f.readline()
if line == "":
... |
28583f2573d3bb5fdf6123605a7d9defdc3ab08c | Dosmingge/Algorithm | /string/lesson1.py | 219 | 3.65625 | 4 | def res(str):
pass
str1 = "Let's take LeetCode contest"
arr = []
arr2 = str1.split(' ')
a = len(arr2)
for i in range(a):
aa = list(arr2[i])
aa.reverse()
arr.append("".join(aa))
print(" ".join(arr))
|
cf68181c87d3fbe5c1952584c7c1f0ec76b79d50 | Danielporcela/Meus-exercicios-phyton | /mostra o nome e indica o 1° e o ultimo no separadamente .py | 346 | 4.03125 | 4 | #027: Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o último nome separadamente.
n=str(input('Digite seu nome completo :')).upper().strip()
nome = n.split()
print(' Prazer em te conhecer !')
print('Seu primeiro nome é {}'.format(nome[0]))
print(' seu ultimo nome é {} '.forma... |
b831fbcb33398048b746e9d4da66dab33821304c | Danielporcela/Meus-exercicios-phyton | /multiplicação e raiz quadrada .py | 210 | 4.03125 | 4 | n1=int(input('digite um numero:'))
a = n1 * 2
b = n1 * 3
c = n1 ** (1/2)
print('conforme o numero digitado {},\n sua multiplicação é {},\n o triplo é {} ,\n e a raiz quadrada é {:.2f}'.format(n1,a,b,c))
|
ebdd700ab852f41d733e383fb33d205271cbd050 | Danielporcela/Meus-exercicios-phyton | /sistema de pagamentos ,exercicio 44 mundo 2 .py | 1,121 | 3.796875 | 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 até 2x no cartão: preço formal
#– 3x ou mais no cartão: 20% de juros#
print('================== LOJA AS... |
bb66fc37ca5c19cc8b80bbb6899e492d0397e3df | Danielporcela/Meus-exercicios-phyton | /soma IMC dando resultado grau massa muscular .py | 777 | 4.03125 | 4 | #Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu Índice de Massa Corporal (IMC) e mostre seu status, de acordo com a tabela abaixo:
#– IMC abaixo de 18,5: Abaixo do Peso
#– Entre 18,5 e 25: Peso Ideal
#– 25 até 30: Sobrepeso
#– 30 até 40: Obesidade
#– Acima de 40: Obesidade Mórbida
pes... |
944d4e0f01699e35dce775c8b8b6543c1f034ff5 | Danielporcela/Meus-exercicios-phyton | /soma de cateto e oposto de cateto .py | 937 | 4 | 4 | #faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triangulo retrangulo , calcule e mostre o comprimento da hipotenusa#
co=float(input('digite o comprimento do cateto oposto:'))
ca=float(input('digite o comprimento do cateto adjacente :'))
soma= (co **2 + ca **2)**(1/2)
print(' A hipo... |
442531f67bbcb62c307af612b26aa1d4d12d5bcf | gkalidas/Python | /practice/censor.py | 658 | 4.3125 | 4 | #Write a function called censor that takes two strings, text and word, as input.
#It should return the text with the word you chose replaced with asterisks.
#For example:
#censor("this hack is wack hack", "hack")
#should return:
#"this **** is wack ****"
#Assume your input strings won't contain punctuation or upper cas... |
dbef6fd0c8e9b355265aca9d6486e6754cf8d4ff | gkalidas/Python | /queries/insert.py | 495 | 3.515625 | 4 | #insert into table query using python
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root",password="shA2189",database="sakila")
mycursor = mydb.cursor()
sql = "insert into products (id,name) values( %s,%s)"
val = [
(1,"John"),
(2,"Peter"),
(3,"Amy")
]
mycursor.executemany(sql,val)
#w... |
ea3870b38fd2087b46839f6cb8dc0eb72a3c5792 | gkalidas/Python | /examStatistics/sumOfGrades.py | 436 | 4.09375 | 4 | #On line 3, define a function, grades_sum, that does the following:
#Takes in a list of scores, scores
#Computes the sum of the scores
#Returns the computed sum.
#Call the newly created grades_sum function with the list of grades and print the result.
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
... |
931811c96b29f0e98e6d657a26074b334dbae039 | gkalidas/Python | /practice/removeDuplicates.py | 803 | 3.9375 | 4 |
l = [2,4,5,2,3,8,5,9]
#This one doesn't give output logically
def remove_duplicates(l):
nl = l
for x in l:
if x in l:
print x
nl.remove(x)
print(nl)
return nl
#Answer by codecademy
def remove_duplicates(inputlist):
if inputlist == []:
return []
# Sort the input list from low ... |
d9317f6924fd4b7bc090ebf47acd8ee995d219ba | gkalidas/Python | /practice/is_int.py | 122 | 3.84375 | 4 | #check if the number is int or not?
#ex 7 == 7.0
def is_int(x):
if x==int(x):
return True
else:
return False
|
6ae7d434d182efebea2ee20dd122860f6bafde8b | TamaraJBabij/ReMiPy | /dictOps.py | 550 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# Applies a function to each value in a dict and returns a new dict with the results
def mapDict(d, fn):
return {k: fn(v) for k,v in d.items()}
# Applies a function to each matching pair of values from 2 dicts
def mapDicts(a, b, fn):
return {k: fn(a[k], b[k]) for k in a.keys()}
# Adds... |
5128f9f503d83cfe47b5b937c1ea5f3283a092f7 | RyuichiSai/Atcoder | /at03/at03b.py | 397 | 3.5625 | 4 | S = input()
T = input()
for i in range(len(S)):
if S[i] == T[i]:
pass
elif S[i] == "@" and T[i] == "@":
pass
elif S[i] == "@" and T[i] in {"a", "t", "c", "o", "d", "e", "r"}:
pass
elif T[i] == "@" and S[i] in {"a", "t", "c", "o", "d", "e", "r"}:
pass
el... |
c845b396613e7ffab43b007fcbb4e8474cc78e70 | RyuichiSai/Atcoder | /at32/at32a.py | 254 | 3.671875 | 4 | import math
a = int(input())
b = int(input())
n = int(input())
ans = a * b / math.gcd(a, b)
if ans >= n:
print(int(ans))
exit()
else:
while ans < n or ans % a != 0 or ans % b != 0:
ans += min(a, b)
print(int(ans))
|
2219e11a951880642c58c797cd55d66106e90b18 | HellooYing/algorithm_exercise | /大二刷的python的/hn汉诺塔.py | 425 | 3.875 | 4 | class Solution:
"""
@param n: the number of disks
@return: the order of moves
"""
def towerOfHanoi(self, n):
l=[]
def move(n,a="A",b="B",c="C"):
if n==1:
l.append("from "+a+" to "+c)
return l
move(n-1,a,c,b)
move(1,a... |
13110548e8cdb338274bf26e0cd65c733fff3487 | HellooYing/algorithm_exercise | /大二刷的python的/lb链表两数相加.py | 1,516 | 3.65625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
a=l1
b=l2
whi... |
551f6afd49c1593a323d0b3cc61bb068f99b51a9 | Atenatek/euler-project | /problem4/euler4.py | 511 | 4.03125 | 4 | #Largest palindrome product
#Problem 4
#A palindromic number reads the same both ways.
#The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
palindromes = []
for a in range(999,99,-1):
for b in range(... |
c54c296c81e00ab8bd30a45db755aa11f7c9ebf1 | Atenatek/euler-project | /problem6/euler6.py | 1,257 | 3.84375 | 4 | #Sum square difference
#Problem 6
#The sum of the squares of the first ten natural numbers is,
#1**2+2**2+...+10**2=385
#The square of the sum of the first ten natural numbers is,
#(1+2+...+10)**2=55**2=3025
#Hence the difference between the sum of the squares of the first
#ten natural numbers and the square of ... |
ff3197175905c7323a4fa826c90911925b7541fd | vandevey/BachelorDIM-Lectures-Algorithms-2019 | /S1_algotools_teacherdemo.py | 3,217 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 26 14:18:46 2019
@author: vandevey
"""
# --- Premiers pas ---
'''
print('Galettes saucisses')
myVariable = 0
print('My variable = ', myVariable)
'''
# --- Algorithm 1 ---
'''
def mySum(param1, param2) :
Function that sums two input params int value
retu... |
b174f58fcd267c66c22ef7d9400fa25193622052 | elim168/study | /python/basic/concurrent/thread/test02_threading_test.py | 478 | 3.84375 | 4 | # 通过threading.Thread()创建线程
import threading
import time
def func1():
print('func1 start')
time.sleep(3)
print('func1 end')
def func2():
print('func2 start')
time.sleep(3)
print('func2 end')
t1 = threading.Thread(target=func1)
t2 = threading.Thread(target=func2, name='thread-name-func2') ... |
7a8beb9f3174261931dd3299aaed8ab14caa8db3 | elim168/study | /python/basic/file/test01.py | 2,470 | 3.78125 | 4 | # 通过open()方法可以打开一个文件,打开的模式默认是只读,即r,其它可选项包括:
# w:写
# a:追加写
# b:以二进制方式进行操作,默认是以字符进行操作
# +:读写
f = open('/home/elim/file1.txt', 'r') # 默认也是读模式
print(f.name) # 打印文件名
for line in f:
print(line)
f.close()
# 标准的文件打开和关闭操作。try...except...finally
try:
f = open(r'/home/elim/file1.txt', 'w') # 路径前加的r是字符串的语法,表示原始字符... |
d32f13e2649829fc5813503e8fba24dc8727f019 | elim168/study | /python/basic/function/04.filter_test.py | 249 | 3.8125 | 4 | # filter test
# filter函数用于对可迭代对象进行过滤,只筛选出满足条件的元素
a = list(range(1, 10))
def is_even(x):
return x % 2 == 1
result = filter(is_even, a)
print(result)
print(list(result)) # [1, 3, 5, 7, 9]
|
a3cf0c5cba3a6c8d828b64a8f24d6d3e7a5ce5bb | elim168/study | /python/basic/numpy/test05_1dim_slice.py | 999 | 4.0625 | 4 | # 对一维的ndarray进行索引下标访问和切片
import numpy
ndarray = numpy.arange(10)
print(ndarray) # [0 1 2 3 4 5 6 7 8 9]
# 通过索引访问ndarray的元素
print(ndarray[5]) # 索引为5的元素,即5
print(ndarray[-3]) # 倒数第3个元素,即7
# 切片。ndarray的切片和list的切片是一样的,语法都是[start:end:step]
print(ndarray[:]) # 输出整个数组
print(ndarray[5:]) # 输出从索引5开始之后的元素组成的数组。[5 6 7 ... |
dc62c02b75dbc30d90ba2df11dc1a02d86a96ad3 | elim168/study | /python/basic/matplotlib/05.绘制一元二次方程曲线.py | 120 | 3.5 | 4 | import matplotlib.pyplot as plt
x = list(range(-100, 100))
y = [2 * i ** 2 - 100 for i in x]
plt.plot(x, y)
plt.show()
|
d6dffc62229cbd1851ed4bfd7b3244313576eb59 | elim168/study | /python/basic/function/09.partial_test.py | 404 | 4.15625 | 4 | # 测试partial函数
# functools的partial函数可以把一个函数的某些参数固定住,然后返回新的函数。比如下面把int函数的base参数固定为2返回new_int函数,之后new_int都以二进制对字符串进行整数转换。
import functools
new_int = functools.partial(int, base=2)
print(new_int('111')) # 7
print(new_int('1110')) # 14
print(new_int('1110101')) # 117
|
765baeb21f7ae5b9c16822ae9da8d62fec5f5e5a | elim168/study | /python/basic/exception.py | 1,458 | 3.796875 | 4 | # -*- coding: UTF8 -*-
def test1():#主动抛出一个异常
try:
raise ValueError
print('Success')
except ValueError:
print('发生了ValueError')
#raise#加上raise可以把该异常重新原封不动的抛出
def test2(flag=True):#通过flag控制是否抛出异常,默认是True
try:
if flag:
raise ValueError('Exception Test')
... |
067a9bce60948cf10fa1d6f441d1b20759fa0d8b | elim168/study | /python/basic/sort_algorithm/selection_sort.py | 526 | 3.875 | 4 | # 选择排序
# 它的思想是第一次选择最小的数字与第一个位置的数字交换,第二次在剩余的数字中选择最小的与第二个位置交换,依次类推。
def sort(lista):
n = len(lista)
for i in range(n):
min_index = i
for j in range(i+1, n):
if lista[min_index] > lista[j]:
min_index = j
if min_index != i:
lista[i], lista[min_index] =... |
dccdeed268be18dba9142290de732b5e20ad30c8 | elim168/study | /python/basic/numpy/test02_array.py | 498 | 4.125 | 4 | import numpy
# 创建一维的数组,基于一维的列表
ndarray = numpy.array([1, 2, 3, 4, 5, 6])
print(ndarray)
print(type(ndarray)) # <class 'numpy.ndarray'>
# 创建二维的数组,基于二维的列表。三维/四维等也是类似的道理
ndarray = numpy.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]])
print(ndarray)
# 通过ndmin指定最小维度
ndarray = numpy.array([1, 2, 3], ndmin=5... |
cbd9d1584a35c3c18d2d337e8c90daeb1b196da5 | elim168/study | /python/basic/sort_algorithm/quick_sort.py | 1,607 | 4.03125 | 4 | # 快速排序
# 它的思想是取需要排序的数组中的第一个数作为基准,然后依次比较,把小于该基准数的都放左边,大于该基准数的都放右边。然后左右两边继续按照此方法进行,直到排序完成。
import random
def sort(lista, start, end): # 对列表中的某一段进行快排
if start >= end: # 索引超出或相等时退出递归
return
low = start # 低位索引
high = end # 高位索引
mid = low # 基准数据的索引,初始值为地位索引
while low < high:
while low <... |
7addf38d9d6172a50719292116de8bb041cb8452 | elim168/study | /python/basic/sqlite3/test1.py | 1,818 | 4 | 4 | import sqlite3
database = 'database_data_file.db' # 数据库文件
connection = sqlite3.connect(database) # 创建数据库连接
cursor = connection.cursor() # 创建游标对象
create_sql = '''create table t_user(
id integer primary key autoincrement,
username varchar not null,
password varchar not null
)
'''
try:
cursor.execute... |
32f3c70378d73f4c780c4a4ff8715e154b3ad7a5 | HSShin0/coding_exercises | /cpps/96-Unique_Binary_Search_Trees.py | 940 | 3.546875 | 4 | class Solution:
def __init__(self):
self.memory = [1, 1]
# n = 0 은 numTrees 구현 시 편리함을 위해 1 로 설정.
# n = 1 인 경우, 1 개의 binary search tree 존재.
def numTrees(self, n: int) -> int:
if n < len(self.memory):
return self.memory[n]
num_trees = 0
... |
085f60472146523cbf36d36e75ba002cba379e10 | nachoba/python | /introducing-python/003-py-filling.py | 2,302 | 4.59375 | 5 | # Chapter 3 : Py Filling: Lists, Tuples, Dictionaries, and Sets
# ------------------------------------------------------------------------------
# Before started with Python's basic data types: booleans, integers, floats, and
# strings. If you thinks of those as atoms, the data structures in this chapter
# are like m... |
47ddb581030c352e6245d27cf1faf23717f4fd6b | phss/playground | /mini_project/fitting-equations/from-wikipedia.py | 548 | 3.859375 | 4 | # From https://en.wikipedia.org/wiki/Linear_least_squares_(mathematics)
import numpy as np
import matplotlib.pyplot as plt
m = 4
n = 2
input = np.array([
[1, 6],
[2, 5],
[3, 7],
[4, 10]
])
X = np.matrix([np.ones(m), input[:,0]]).T
y = np.matrix(input[:,... |
14a2d410e121286ba14c2196fee0000b9eb11d48 | isabella232/optimizely-platform | /optimizely_platform/utils.py | 363 | 4 | 4 | from itertools import islice
def chunkify(items, chunk_size):
"""Breaks items into evenly-sized chunks.
Args:
items: a list of items of any data type
chunk_size: the number of items to yield as a chunk
"""
items = iter(items)
chunk = list(islice(items, chunk_size))
while chunk:
yield chunk
... |
eb2d640af2f5a5170fcad4c0098739255f627bb6 | marikaSvensson/Knightec | /pythonProgs/code170523/functions.py | 5,626 | 3.828125 | 4 | # These are all the functions/algorithms that are produced - these are called by main.py
# created by Marika Svensson 20170523
# Divide and conquer canonical algorithm (pp 118)
#input : set/sequence of elements
# -------------------- no 1: ---------------------------------------
def divide_and_conquer (S, divide,... |
e62fedb9452489905fd6639ce809b0dea9bbc011 | marikaSvensson/Knightec | /pythonProgs/code170517/dictionaries.py | 1,170 | 3.875 | 4 |
a = [66.25, 333, 333, 1, 1234.5]
print a.count(333), a.count(66.25), a.count('x') #2 1 0
a.insert(2, -1)
a.append(333)
print a #[66.25, 333, -1, 333, 1, 1234.5, 333]
print a.index(333) #1
a.remove(333)
print a #[66.25, -1, 333, 1, 1234.5, 333]
a.reverse()
print a ... |
6d8665125a6f08de9906c7e09070c3cbf05765bc | NicoloCervo/CUBIO | /Skeleton.py | 5,422 | 3.875 | 4 | from constants import WIDTH, HEIGHT, WIN_LEN
class Skeleton:
""" basic game object with logic, operations on the board and winner detection
"""
def __init__(self):
self.board = [[0 for col in range(WIDTH)] for row in range(HEIGHT)]
self.result = 0
self.seq_list=[]
def show(sel... |
b31cc278f8564b3fb9e22d4cc28c9520e7ee98bf | stvnSzabo/ccOW1 | /if/if10.py | 283 | 3.890625 | 4 | a = int(input("a?"))
b = int(input("b?"))
c = int(input("c?"))
if ((a * a) + (b * b) == (c * c)):
print("C az átofogó")
elif ((c * c) + (b *b) == (a * a)):
print("A az átfogó")
elif ((c * c) + (a *a) == (b * b)):
print("B az átfogó")
else:
print("Invalid")
|
689a33c0dbbc2d386c2df11d3a1cd16de193ffe3 | stvnSzabo/ccOW1 | /for loop/loop7.py | 168 | 3.96875 | 4 | n = int(input('N?'))
def Fibonacci(n):
f0, f1 = 0, 1
for i in range(n):
yield f0
f0, f1 = f1, f0+f1
fibs = list(Fibonacci(n))
print(fibs)
|
8677f24656f9792dc968db44095895bee23ef469 | myke-oliveira/curso-em-video-python3 | /desafio 64.py | 535 | 3.953125 | 4 | #! /usr/bin/python3.6
print(
'''Crie um programa que leia \033[34mvários
números\033[m inteiros pelo teclado. O programa só
vai parar quando o usuário digitar o valor
\033[33m999\033[m, que é a condição de parada. No final,
mostre quantos números foram
digitados e qual foi a soma entre eles.
\033[37m(desconsiderando ... |
37eb9929352029c4ae42099cda1d8b29103a9f9d | myke-oliveira/curso-em-video-python3 | /desafio22.py | 734 | 4.40625 | 4 | ''' Crie um programa que leia o nome completo de uma pessoa e mostre:
O nome com todas as letras maiúsculas.
O nome con todas minusculas.
Quantas letras ao todo (sem considerar espaços).
Quantas letras tem o primeiro nome.'''
print('Digite o nome completo da pessoa: ')
nome = input().strip()
print()
print(... |
8dea6f08a3cbbd66f7f1ec744b8f4272c97c9b9b | myke-oliveira/curso-em-video-python3 | /desafio018.py | 628 | 3.921875 | 4 | print('{:*^50}'.format('Desafio 18'))
print('Faça um programa que leia um ângulo qualquer e mos-')
print('tre na tela o valor do seno, cossenoe tangênge desse')
print('ângulo.')
print('{:*^50}'.format('Início'))
import math
while True:
try:
deg = float(input('Digite o valor do ângulo: '))
b... |
16cf2b2aa16c2b1cb1d567ab2d94de6b8b853106 | myke-oliveira/curso-em-video-python3 | /desafio 46.py | 358 | 3.546875 | 4 | #! /usr/bin/python3.6
print(
'''Faça um programa que mostre na tela
uma contagem regressiva para o estouro
de fogos de artifício, indo de 10 até 0,
com uma pausa de 1 segundo entre eles.'''
)
from time import sleep
for i in range(10, 0, -1):
print(i, end = '', flush=True)
sleep(1)
print('\r \r', end =... |
561c3c6ecf588aeeb77f39243d5d4ad76e96e134 | myke-oliveira/curso-em-video-python3 | /desafio007.py | 571 | 3.78125 | 4 | print('{:=^50}'.format('Desafio 07'))
print('Desenvolva um programa que leia as duas')
print('notas de um aluno, calule e mostre a sua')
print('média.')
print('{:=^50}'.format('Início'))
while True:
try:
n1 = float(input('Digite a 1ª nota: '))
break
except ValueError:
print('Va... |
a85499301d20b7b0938662468d31c0c084377fc1 | myke-oliveira/curso-em-video-python3 | /desafio26.py | 531 | 4.03125 | 4 | ''' Faça um programa que leia uma frase pelo teclado e mostre:
Quantas vezes aparece a letra "A"
Em que posição ela aparece a primeira vez.
Em que posição ela aparece a última vez.'''
frase = input('Frase: ').strip()
MAIUSCULA = frase.upper()
print('Quantas vezes aparece a letra A: {}'.format(MAIUSCULA.count(... |
74a4863a95bd3767b24689c22262721a7a681993 | myke-oliveira/curso-em-video-python3 | /desafio 50.py | 352 | 3.796875 | 4 | #! /usr/bin/python3.6
print(
'''Desenvolva um programa que leia seis
números inteiros e mostre a soma apenas
daqueles que forem pares. Se o valor
digitado for ímpar
desconsidere-o.'''
)
soma = 0
for i in range(1, 7):
entrada = int(input('Número {}: '.format(i)))
if entrada % 2 == 0:
soma += entrada
pr... |
06655d49ed66cd5c5c8d8f0706e63653ed58269d | myke-oliveira/curso-em-video-python3 | /desafio 40.py | 355 | 3.828125 | 4 | #! /usr/bin/python3.6
n1 = float(input('Primeira nota: '))
n2 = float(input('Segunda nota: '))
média = (n1 + n2) / 2
print('Média: {:.2}'.format(média))
if média < 5:
print('O aluno está \033[31mREPROVADO\033[m.')
elif média < 7:
print('O aluno está em \033[32mRECUPERAÇÃO\033[m.')
else:
print('O alno está ... |
209d380eeb75040a3911371e2b1297f210c66adb | berketuna/py_scripts | /reverse.py | 253 | 4.40625 | 4 | def reverse(text):
rev_str = ""
for i in range(len(text)):
rev_str += text[-1-i]
return rev_str
while True:
word = raw_input("Enter a word: ")
if word == "exit":
break
reversed = reverse(word)
print reversed
|
3912d6e983aafb61955657501fd969fda3b3e904 | kanglicheng/bites_of_py | /bite29.py | 418 | 3.53125 | 4 | def get_index_different_char(chars):
alnum_count, other_count = 0, 0
alnum_index, other_index = 0, 0
for i, c in enumerate(chars):
if str(c).isalnum():
alnum_count += 1
alnum_index = i
else:
other_count += 1
other_index = i
return alnum_ind... |
33a09a6900707777ceed99bc5c2a21e4121f4ced | dhvfanny/chainer-abcnn | /bin/preprocess/jsonify.py | 849 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
WikiQAの中身をtokenizeしたものに置換するスクリプト
1行1jsonで吐きます
"""
import sys
import argparse
import json
from itertools import groupby
def main(fi):
for line in fi:
data = line.strip().split("\t")
question_id = data[1]
document_id = data[3]
sentence_id = data[5]
... |
9df6ba31f748598052145a2cd42024f5baaa43e3 | iangornall/week1 | /string/upper.py | 156 | 3.84375 | 4 | string = 'a string'
newstring = ''
for letter in string:
if letter = ' '
newstring += ' '
newstring += chr(ord(letter) - 32)
print newstring |
e501ddef8748d4e42d064b0182d03da18af14502 | iangornall/week1 | /103/weekday.py | 137 | 3.6875 | 4 | week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
day = int(raw_input('Day (0-6)? '))
print week[day] |
e9ae03de5442b88dfdcb1645f7c9b336945f9403 | iangornall/week1 | /string/reverse.py | 125 | 3.765625 | 4 | string = 'okay sure'
print string[::-1]
for i in range(len(string)):
newstr += string[len(string) - i - 1]
print newstr |
ee0415fa2d77e7c31de874b28ac4b4a4a93f5d45 | YinhaoHe/Python-AI-teaching | /solutions/3_solutions/3.7.py | 390 | 3.75 | 4 | import pandas as pd
s1 = pd.Series([1,2,3,4,5,12,11,123])
s2 = pd.Series(["a","b","c","d","e","f","g","h"])
df = pd.DataFrame(columns=["numbers","letters"])
df["numbers"] = s1
df["letters"] = s2
# df = pd.DataFrame({"numbers":s1, "letters":s2})
df.size
# add a column
df.insert(2, "more letters", ['g','c'... |
532a96c8eade60640e5b10f502f3e4b66ba2afaa | JacintaRoberts/mcmc-cuda | /sample_generator.py | 1,263 | 3.59375 | 4 | import numpy as np
from numpy.random import multivariate_normal
import sys
import matplotlib.pyplot as plt
# USAGE: python sample_generator <n_dim> <n_samples>
# Generates samples from multivariate normal distribution using in-built function from numpy and saves to text file
# Requires the mean (1-D array of length N)... |
a06cfcb53addfa0d484a3a0599721b9a2cdd13b3 | abirjameel/Projects | /Naive Bayes Classifier/Naive Bayes Classifer.py | 3,439 | 3.953125 | 4 |
# coding: utf-8
# In[5]:
import operator
# In this problem we will find the maximum likelihood word based on the preceding word Fill in the NextWordProbability procedure so that it takes in sample text and a word,and returns a dictionary with keys the set of words that come after, whose values are the number of ti... |
e83dcca5abdf4b6632f5049925662c6252493a60 | samuel-gf/python | /Arrays/01Lista.py | 130 | 3.578125 | 4 | # -*- coding: utf-8 -*-
lista = [1, 7, 8, 2, 5, 6]
print (lista[0]+lista[1])/2
print "La longitud de la lista es de",len(lista)
|
cbc122380fe8e4ce1d672c039944647f8ee60696 | Nireplag/computational_vision | /functions.py | 460 | 3.65625 | 4 | def isRGB(img):
"""Check if an image is colored (3 channels)
Input:
image
Output:
Boolean
"""
if img.shape[2] == 3:
return True
else:
return False
def new_shape(img,scale):
if scale > 1:
scale = 1 - scale/100
else:
scale... |
5519c754a70bb87090e3c976f4fbc27bf59e6d51 | BEricDavis/sqlalchemy_stuff | /things.py | 2,479 | 3.515625 | 4 | import sqlalchemy
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo=True)
# create a declaratice base class
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
# define a class representing a User table
from sqlalchemy import Column, Integer, String... |
80c5bb85b36af47088f29faa067ab536fd57df5e | guszejnovdavid/PAWS_acronym_generator | /paws_acronym/paws_acronym.py | 8,586 | 3.890625 | 4 | #!/usr/bin/env python
"""
Algorithm that lists possible English acronyms from a listed keywords.
It is inspired by ACRONYM (Acronym CReatiON for You and Me, https://github.com/bacook17/acronym) but unlike ACRONYM this algporithm creates proper... |
f155e17ee962cb4b59a2b0d660f26f2f35c08b5b | bruxkpo/recuperacion | /recuperacion/Ejer3.py | 1,493 | 3.765625 | 4 | import random
def dados():
#Darme una variable entera que indica la cantidad de tiradas que se hacen
tiradas = int (input("Ingrese la cantidad de tiradas que quiere realizar: "))
#creo array para guardar tiradas
ArrTiradas = []
#creo array para guardar un contador que indica la cantidad de... |
864a7378a0befccbcd73ea801af84d386a1cdbe5 | demxic/Tripper | /models/fileparsers.py | 2,124 | 3.546875 | 4 | """This module holds functions needed to read pbs.txt files and turn them into schedule classes"""
from models.regularexpressions import trips_total_RE, trip_RE, dutyday_RE, flights_RE
from typing import List, Dict
def number_of_trips_in_pbs_file(pbs_file_content: str) -> int:
"""Searches for the 'Total number of... |
77f9e24bd93c812926b01bc3bd427851ed8eeb13 | yufengyuanx/SchoolProject | /Data Mining/random-forest/src/DecisionTree.py | 8,087 | 3.75 | 4 | from math import log # for calucate the entropy
__author__ = "Yufeng Yuan"
__email__ = "Yufeng_Yuan@student.uml.edu"
class TreeNode(object):
def __init__(self, isLeaf=False):
self.isLeaf = isLeaf
self.attribute = None
self.left = None # left child
self.right = None # ri... |
672d563611dc157171fedfe7bbc713e03934c9f1 | welcomesoftware/adminimarket | /index.py | 1,499 | 3.8125 | 4 | # importa ttk que es la biblioteca que nos permite utilizar toda la interfaz gráfica
from tkinter import ttk
# importa todos los elementos de la interfaz gráfica, botones, listas, etc.
from tkinter import *
# importa la biblioteca para la conexión a la base de datos
import sqlite3
# utizaremos el paradigma POO para c... |
6ff118098580cca635bd6843bff9f19e85244da2 | jamiebull1/geomeppy | /geomeppy/geom/segments.py | 2,008 | 3.671875 | 4 | """
Segment class, representing a line segment.
"""
from typing import Any, Iterator # noqa
from .vectors import Vector3D
from ..utilities import almostequal
if False:
from .polygons import Polygon3D # noqa
class Segment(object):
"""Line segment in 3D."""
def __init__(self, *vertices):
# ty... |
8709008cfd28b61340935b65998dd89b3d29d578 | ijw9209/Python | /Py01_Hello/com/test02/controll01_iftest.py | 396 | 4 | 4 | # -*- coding:utf-8 -*-
# Hello World! 출력
print('Hello, World!')
# Hello , Python! 출력
print('Hello,',end=''); print('Python!')
a = 5
if a == 10:
print('10 입니다.')
else:
print('10 아닙니다.')
if a == 10:
print('10 입니다.')
elif a == 5:
print('5 입니다')
else:
print('5도 아니고 10도 아닙니다.')
... |
268ba2c599b63d17acd0dc8ac5801797a6d665ca | nikhalster/ComputerLab3 | /DiningPhilosophers/diningPhilosopher.py | 1,473 | 3.765625 | 4 | import threading
import random
import time
class Philosophers(threading.Thread):
running = True
def __init__(self, xname, leftfork, rightfork):
threading.Thread.__init__(self)
self.name = xname
self.leftfork = leftfork
self.rightfork = rightfork
def run(self):
whi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.