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
8e2980c1b42938d1858988602dc5379cc6e2d75e
yyyuaaaan/python7th
/crk/10.5h.py
1,201
4.09375
4
"""__author__ = 'anyu' 11.5 Given a sorted array of strings which is interspersed with empty strings, write a method to find the location of a given string. Example: ["at","","","","ball","","","car","","","dad","",""] will return 4 Careful consideration should be given to the situation when someone searches for the em...
d894d51d718e0643db129c32bdc3d9511387b0fd
yyyuaaaan/python7th
/crk/4.bst_seque.py
1,516
4.03125
4
# BST Sequences:A binary search tree was created by traversing through an array # from left to right and inserting each element. Given a binary search tree with # distinct elements, print all possible arrays that could have led to this tree. # 2 1 3 # 2 3 1 # a bit wrong with this problem, all permutations can crea...
41e196e4c8a5ea65e935e8bead81263a79bb8196
yyyuaaaan/python7th
/Leat/Partition List.py
1,715
3.71875
4
"""__author__ = 'anyu' Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. For example, Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5. // Co...
87b6ed27dfbc3b3d68a809dca54e673cb1d8ee95
yyyuaaaan/python7th
/crk/4.7.py
3,236
3.84375
4
"""__author__ = 'anyu' First Common Ancestor Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree. If this were a binary search tree,we could modify the find operation...
a3048a4f137c481b6a29b0a5cf240878dd6219e9
yyyuaaaan/python7th
/crk/8.12h_eightqueen.py
1,568
3.90625
4
"""__author__ = 'anyu' 8.8 Write an algorithm to print all ways of arranging eight queens on a chess board so that none of them share the same row, column or diagonal. Observe that since each row can only have one queen, we don't need to store our board as a full 8x8 matrix. We only need a single array where column [ro...
678572b689e5a98f09716619cec297aa844853e7
yyyuaaaan/python7th
/crk/10.1.py
1,085
4.0625
4
"""__author__ = 'anyu' Sorted Merge You are given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order. easy and tricky """ """# wrong def arraymerge(a,b,lena,lenb): for i in reversed(range(lena + lenb-1)): if b[i]> a[lena-1-i]...
33be1300d87566fb2f142b32e6a1897eb720c21e
yyyuaaaan/python7th
/crk/4.6.py
1,501
3.828125
4
"""__author__ = 'anyu' Successor Write an algorithm to find the next node ( in-order successor) of a given node in a binary search tree where each node has a link to its parent. assume there is a parent link to every node, but don't need it This is not complex problem very tricky to code perfectly. sketch out pseudocod...
574ea273d93eaa9ff9e1c055c6b699b0685e8b02
rshatkin/dev-installday
/chapter2_exercises.py
965
4
4
# it seems that the value of o1, 010, 0100 and 01000 respectively are: 1, 8, 64, and 512 # each is the number before multipled by 8 # if we are dealing with octal number systems, only the numbers 1-7 are valid, # which is why 02492 is invalid (9 is not octal) # so the first number '0' is the number of 1's (0), then t...
a30807a4a4d8f44393d3b9c085c57df16d90d2c6
IntotheLine/small-games-to-play
/#Random Drink Machine.py
393
3.65625
4
# Random Drink Machine print('Hello There, please enter your Name') name = input() print(name + 'you have the choice of alcohol, supplements will be random choiced') alcohol = ['Vodka', 'Gin', 'Bacardi', 'Havanna 7 Anos'] supplements = ['Tonic Water', 'Coke', 'Sprite', 'Champagne'] print(alcohol) print('Wähle zwisch...
6bf409f97f35f82ad2b65cc64b666ec142f8b521
Mika-IO/backend-technical-assessment
/chesschallenge/chess/chess.py
1,601
3.703125
4
from itertools import product def validate_coordinate(coordinate): """ Return True if coordinate is valid, else return False """ if len(coordinate) != 2: return False valid_letters = ["a", "b", "c", "d", "e", "f", "g", "h"] valid_numbers = ["1", "2", "3", "4", "5", "6", "7", "8"] ...
a685228d2129c3e08123ae8e321f0449134adda7
cMckibbin-dev/Python_booking_System
/gui/top_level_functions.py
2,097
3.6875
4
from tkinter import * from classes import * from gui import view_details as vD from gui import update from gui import CalendarDialog def calendar_popup(event, master, date_string, startDate=None, minDate=None): """function to display calendar dialog and changes value of StringVar to the selected value""" c = ...
08e4a844963910ad7f62052c1faf79beffe1d383
Fjmr18/IPS
/CPeD/Labs/Lab2/fiboSeq.py
586
3.859375
4
# Computação Paralela e Distribuída 2020/2021 # Aluno: Fernando Ramalho 200290040 BS (BrightStart 2ª Edição) # Aluno: Antonio Costa 200221097 (BrightStart 2ª Edição) ############################################# import checkSys as check print(check.get_processsor_info()) import random def fibonacci(input): a, b =...
155fd43d43338e0fb9656b65dd7bf10292e28f89
adammck/rapidsms-community-apps
/reporting/utils/dates.py
1,386
3.640625
4
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import re, datetime DELIMITER = r"(?:\A|[\s;,\*]+|\Z)" PATTERN = r""" (?P<day>\d{1,2}) (?P<delimiter>[.-/\s]) (?P<month>\d{1,2}) \2 (?P<year>\d{2,4}) """ REGEX = re.compile(DELIMITER + PATTERN + DELIMITER, re.VERBOSE) def extract_date(text)...
e982926e03e14625638025dabb2fb057e6479397
kucherskyi/python-for-qa
/lesson2-2/lesson2_2-4.py
304
3.9375
4
""" Write program to evaluate (a or not b) and (c or not a) expression for boolean varibles a, b, c showing result for all possible variables combinations. """ for a in (True, False): for b in (True, False): for c in (True, False): print ((a or not b) and (c or not a))
aed6734640495affff997ad2debd43a31126bd49
kucherskyi/python-for-qa
/lesson2-1/level1-3.py
385
4.09375
4
""" Print unique elements from any given list or tuple. """ import random def unique(given): return "List of unique elements :{}".format(list(set(given))) """ Examples """ l = [random.randint(0, 100) for i in range(50)] t = tuple(random.randint(0, 100) for i in range(50)) print "List " + st...
cb4b0299a4e26252942ea5a29006de7e55aed954
Maahrii/Tic_Tac_Toe
/main game.py
4,568
3.625
4
import pygame def drawGrid(): global screen blockSize = 300 # Set the size of the grid block for x in range(0, width, blockSize): for y in range(0, height, blockSize): rect = pygame.Rect(x, y, blockSize, blockSize) pygame.draw.rect(screen, B...
3108059e081c4c2d0050e9cf52068f059655259e
conor-chakra/Night
/compareOperators.py
234
4.0625
4
temperature = 30 if temperature == 30 : print('It is a hot day') if temperature >30: print(' it is a really hot day') if temperature <30 : print(' it is a cold day') if temperature >20: print ('it is a lovely day')
655112b4b828531685b3b39b9e3e61def1d932f1
conor-chakra/Night
/list.py
103
3.78125
4
x= [1,2,3,4,6,3,7,4,7,2,1,4] print(x) x.append(9) print(x) x.insert(3,2) x.reverse() x.sort() print(x)
3955d72e1ee88ffee04c8de9d88f370689d8bb1a
Shitong91/python
/02. python基础/04.if/exercise.py
242
3.78125
4
height = 1.75 weight = 80.5 bmi = weight/pow(height,2) if bmi<18.5: print('Xiao ming is too light') elif bmi<25: print('Xiao ming is normal') elif bmi<28: print('Xiao ming is fat') elif bmi<32: print('Xiao ming is too fat')
fbef4cfaaf327607c73811ab12952fd754f1eef7
Shitong91/python
/03.面向对象/04.实例属性和类属性/anyattr.py
141
3.5625
4
class Student(object): def __init__(self, name): self.name=name s = Student('Bob') s.score = 90 t = Student(20) print(t.score)
45ddf4612af80d6d83230cc7f0d32ad1a9ec96f3
hickemj/python
/WhileLoopPwordTestADV.py
401
3.71875
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 10 14:03:38 2019 @author: HickeMJ """ correct_password = "python123" name = input("Enter your name: ") lastname = input("enter your last name: ") password = input("enter password: ") while correct_password != password: password = input("Wrong password! Enter Again: ...
2faf313d491a80f71de20c8568579ec38a519ed7
eduardohenriquern/python-didatic-examples
/carro.py
679
3.5
4
# Criar função que recebe números inteiros e informa qual é o maior # Criar função que recebe um lista de números inteiros e imprime quais são pares ou impares class Carro: # atributo fixo. Pertencente a todos os carros rodas = 4 # Chamamos de atributo da classe. Não muda. # Função construtora. #Cri...
21bdadf6187df552b94a35a5a28105861f9e00b2
tnguyenswe/CS20-Assignments
/Strings/Nguyen_Thomas_pig_latin.py
4,112
4.0625
4
''' Name: Thomas Nguyen Date: 1/8/20 Professor: Henry Estrada Assignment: Strings (Pig Latin) This program converts any input into pig latin. I also finished all 3 extra credits for this assignment! ''' #Sets vowels to include normal vowels and y. Also includes capital versions as it is necessary for extra credit. vow...
b5e756f9eec761edbd58127e9ad66d9d0ec3dae5
tnguyenswe/CS20-Assignments
/Variables And Calculations (2)/Nguyen_Thomas_daylight.py
1,071
4.28125
4
''' Name: Thomas Nguyen Date: 1/6/20 Professor: Henry Estrada Assignment: Variables and Calculations (2) This program takes the latitude and day of the year and calculates the minutes of sunshine for the day. ''' #Import math module import math #Gets input from user latitude = float(input("Enter latitude in degrees: "...
67e2936291dc2adfe12f84b791676337398fc07a
tnguyenswe/CS20-Assignments
/Variables And Calculations (1)/Nguyen_Thomas_prog1.py
858
3.96875
4
''' Name: Thomas Nguyen Date: 1/5/20 Professor: Henry Estrada Assignment: Variables and Calculations (1) This is the first program assignment, it takes the prices of multiple items and calculates the subtotal, tax, and total. ''' #Initialize i and price to 0. price=0 i=0 #Gets price input from user. item1 = float(inpu...
2e916f9dedd4f6d7ca053da6cca036a7f1fdbc82
zenjutahi/phonebookapp
/phonebook.py
606
3.53125
4
class Phonebook: def __init__(self): self.contactList = {} def addContact(self, nameVr, numVr): "Method to add contact" self.contactList[nameVr] = numVr return self.contactList def updateContact(self, nameVr, numVr): "Method to update contact" self...
f45c7793bc6e24f5135978a12aa95918dea27ed8
elias-blm/prenom
/TP.py
6,689
3.515625
4
from tkinter import * #importe toute la biblothèque fichier_prenom= open("prenom.csv", "r", encoding='utf8') #ouvre le fichier donnees= fichier_prenom.readlines() #lis l'ensemble du fichier et transforme une ligne en sous-liste fichier_prenom.close() #ferme le fichier del donnees[0] #supprime la première liste ca...
d92a1b19706ccba7b97de83c41f24d1dc92ad7b5
ozmds/Sample-Sorter
/scripts/sortedlist.py
742
3.734375
4
class SortedList: def __init__(self, word_dict): self.words = word_dict self.list = [] def getlist(self): return self.list def spliceintolist(self, word, i): self.list = self.list[:i] + [word] + self.list[i:] def sort(self): for word in self.words.keys(): ...
4fc3f9ed9f2c8de01a6636c9989a68262a46931f
ernestoaguirreco/Apy
/ForConIn.py
544
3.6875
4
tot = 0 for i in [5, 4, 3, 2, 1] : tot = tot + 1 print tot friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends : print 'Happy New Year:', friend print 'Done!' zork = 0 for thing in [9, 41, 12, 3, 74, 15] : zork = zork + thing print 'After', zork smallest_so_far = -1 for the_num in [...
8867ab7473040681363bfda903b22249af8e5025
GGitboy/python
/day2_homework.py
418
4
4
#!/usr/bin/python #-*-coding:utf-8 -*- #author:suancaiyu #学习内容:python运算符 # + - * / % // << >> & | ^ < > <= >= != not and or def main(): print (1+1) print (1-1) print (1*1) print (1/1) print (1%1) #返回除法的余数 if 1: print('good') if True: print(1) if False: print(0) ...
b39ccd32a5b5ac85a66cc2e4ff33bac6095757be
GGitboy/python
/lab3_1.py
3,133
4.15625
4
#!/usr/bin/python3 # 类是抽象的模板 class Dog(object): def __init__(self,name): #类需要一个构造方法,python 中__init__是python的构造方法 self._name = name #定义一个类的时候也可以不需要__init__ 方法 def get_name(self): return self._name # def set_name(self,value): # self._name = value # pirnt(value) def bark(self...
c00c85e46ec34337b0d8e328ff584048e2f2c37a
YaroslavVygovsky/Git_Python
/Тексотвый запис функции.py
173
3.84375
4
x=float(input('x= ')) b=float(input('b= ')) if x<=2: if b<0: print('y= ',-9*x**2-12*b) elif b>=0: print('y= ',3*x**2-8*b) else:print('y= ',32+x)
bb28509701e9bf6794710fa84a26ec5796f26114
YaroslavVygovsky/Git_Python
/Удаляем и добавляем(повтор).py
157
3.75
4
mashin=['sedan','BMW','VAZ','mersedess','honda']; mashin.insert(2,'lamborgini'); del mashin[-1]; del_mashin=mashin.pop(3); print(mashin); print(del_mashin);
9d08fbda594d9139356316f5ac5fb9a7ca03fdf0
Sinder20/Ejercicios1Python
/QuintoEjercicio.py
145
3.625
4
# Imprimir diez veces la serie de numeros del 1 al 10. i=0 j=0 for i in range(0, 10): for j in range(0, 10): j+=1 print(j)
63ed9e4dad8e6ef3b0260e03bb840c949f8b77f4
jtp273/Optimize
/Mapping.py
4,522
3.71875
4
#!python """ A game where the objective is to map tasks onto resources across spans of specific duration to maximize value. The scheduling problem. """ from TaskRsrc import task, rsrc, setup from Schedules import sched class mapping( object ): """ Create a schedule (a mapping) Display a s...
722b1e1ca439affec2aed8d27f674f281ebc36bb
gg/integer_encoding
/src/integer_encoding.py
1,339
4.34375
4
#!/usr/bin/env python # coding: utf-8 from collections import deque def encoder(alphabet): """ Returns an encoder that encodes a positive integer into a base-`len(alphabet)` sequence of alphabet elements. `alphabet`: a list of hashable elements used to encode an integer; i.e. `'0123456789'` is an...
23cf2ce0a7de0a6241751732905e433070db1bfe
taketrung1988/octopusPaul
/FootballOracle.py
9,546
3.734375
4
#!/usr/bin/python3 import datetime from italy.functions.calculations import * debug=0 homeTeam = ItalyTeam() awayTeam = ItalyTeam() homeData=0 awayData=0 country="" nationalTeam = input("Enter first team name: ") country = checkNames(nationalTeam) homeTeam.name = setName(nationalTeam) awayTeam.name = input("Ent...
3fbd6377e2ecb933cbe14f82c24d40742670573a
cccccyclone/TensorFlow
/tf_4.py
2,123
3.609375
4
###################### #一个隐层的MLP测试 ###################### import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #导入mnist数据集 mnist = input_data.read_data_sets("MNIST_data/",one_hot=True) #注册为默认的session,之后的运算也默认跑在这个session里,不同session的数据和运算应该是独立的 sess = tf.InteractiveSession() int_units = 78...
51dc931fc746d6300cff15ef444e3de24e747ca2
Tinggaard/pathfinding
/pathfinding/algs/breadthfirst.py
1,935
3.625
4
import numpy as np from _collections import deque as dq def breadthfirst(self): assert not self.solved start = self.start end = self.end # set initial value start.dist = 0 # bool array visited = np.full((self.y, self.x), False) # initiate vars q = dq([start]) explored = 0 ...
f8770b4d08e2bb4fc716f1729e02c22d91321e15
thkaridis/Chord_Implementation
/Chord_implementation.py
1,402
3.71875
4
import func """Big Data Management - Msc Data Science -1st Programming Assignment Chord - based simulation of a distributed file system""" def __main__(): """This function is the function main which calls all the other functions and runs the Chord Algorithm It also performs some measurements regarding ...
e577ce9dcc33f7f6d3e922511d168a0b83b421da
pedrocr83/algoritm_design
/calc_fibonaccihugemodulus_Pedro.py
728
3.578125
4
def Huge_Fib(n,m): a, b, c = 1, 1, 0 for i in bin(n)[3:]: calc = (b*b) % m a, b, c = (a*a+calc) % m, ((a+c)*b) % m, (calc+c*c) % m if i == '1': a, b, c = (a+b) % m, a, b print (b) n,m = map(int, input().split()) Huge_Fib(n,m) # Uses python3 from functools import lru_cache @l...
d3412198020f18ff5d875c9c30e359dc98d9b216
therumbler/adventofcode
/2020/day_one_part_2.py
1,427
3.9375
4
import copy def _load_numbers(): numbers = [] with open("dayoneinput.txt") as f: while True: number = f.readline().strip() if not number: break numbers.append(int(number)) return numbers def _find_sum_of_2020(numbers): go = True while go: try: number1 = numbers.pop() remaining = copy.dee...
9d8e0c87d1c1c32a22c5b1037a9acb011e783cb5
Puthiaraj1/musicFiles
/examples.py
551
4.03125
4
# text = "Welcome to Python Learning Program" # # capitals = [char.upper() for char in text] # # #print(capitals) # # words = [word.upper() for word in text.split(' ')] # # print(words) # for x in range(1, 31): # fizzBuzz = "fizz buzz" if x % 15 == 0 else "fizz" if x % 3 == 0 else "buzz" if x % 5 == 0 else str(x) ...
a5a34ca8b1c1547daee21ab9092f118668fee04a
anster01/Routing_App
/dijkstra.py
1,136
3.6875
4
def dijkstra(graph, start, end, weight): duration = {} pred = {} for node in graph.keys(): duration[node] = float('Inf') pred[node] = '' duration[start] = 0 all_nodes = list(graph) while len(all_nodes) > 0: shortest = duration[all_nodes[0]] short...
1d1e4b94dd027f14984207de44a7979a2a0038c0
maadalen/machine-learning
/collaborative_filtering/cf.py
4,932
3.796875
4
import argparse import re import os import csv import math import collections as coll import numpy as np def parse_argument(): """ Code for parsing arguments """ parser = argparse.ArgumentParser(description='Parsing a file.') parser.add_argument('--train', nargs=1, required=True) parser.add_ar...
b45103f0455404bc7bdca84104d895a15e928698
CaimeiWang/python3_examples
/003generate_random_number.py
170
3.546875
4
#生成随机数 import random a=random.randint(1,10) #生成一个在[1,10]之间的整数 b=random.uniform(1,10) #生成一个[1,10]之间的实数 print(a) print(b)
eee1d4c5584e43a058e3e78c7399b8bc1550f562
perikarya/rosalind
/rosalind-3.py
385
3.8125
4
''' complementing a strand of DNA: given a DNA string s of max length 1000 bp, returns the reverse complement sc of s ''' f = open("rosalind_revc.txt", "r") s = f.readline().strip() r = s[::-1] rc = "" for i in r: if i == "A": rc += "T" elif i == "T": rc += "A" elif i == "G": r...
273d638b3c2b9ea9bc8e8b32e59f8c45e61e7ef5
sassy27/DAY1
/OOP/Class instance.py
781
4.125
4
class employees: raised_amount = 1.04 num_emp = 0 def __init__(self,first,last,pay): self.first = first self.last = last self.pay = pay employees.num_emp += 1 # prints number of employees by adding after each emp created def fullname(self): return "{} {}". form...
a381fc4ceaa2af27dc823cf1752762ba9275469b
automl/nasbench301
/nasbench301/surrogate_models/bananas/bananas_src/bo/dom/real.py
1,362
3.515625
4
""" Classes for real coordinate space domains. """ from argparse import Namespace import numpy as np class RealDomain(object): """ Class for defining sets in real coordinate (Euclidean) space """ def __init__(self, domp=None, printFlag=True): """ Constructor Parameters: domp - domain parame...
e505770a4825ab3a032dec1616b7c7d540cdaf06
ssoso27/my-studies
/2019/Alth-Py/src/Q42577.py
745
3.78125
4
# https://programmers.co.kr/learn/courses/30/lessons/42577?language=python3 def solution(phone_book): answer = True my_book = {} for phone in sorted(phone_book): temp = my_book.get(phone[0]) if temp: for saved_phone in temp: l = min(len(saved_phone), len(phone)) ...
fe43e66488874ea72964301b944c8eaf0e445fd2
ssoso27/my-studies
/2018/algorithm-walk/day3/homeword002.py
262
3.828125
4
''' 과제 2) 재귀함수를 이용하여 입력 받은 n이하의 피보나치 수열을 구하라. ''' def fibonachi(a, b, n): if ((a + b) <= n): print(a + b, end=',') return fibonachi(b, a+b, n) print('1,1,', end='') fibonachi(1, 1, 100)
4800256e13132f01cfe11079ff1b5b4c692be750
Tofu-Gang/advent_of_code_2019
/day_01/day_01.py
5,059
3.890625
4
__author__ = "Tofu Gang" __email__ = "tofugangsw@gmail.com" from math import trunc """ --- Day 1: The Tyranny of the Rocket Equation --- Santa has become stranded at the edge of the Solar System while delivering presents to other planets! To accurately calculate his position in space, safely align his warp drive, ...
4589928fdb9ae81e9d9d23b509b30a61539ebd8e
rohitx/Zelle-Python-Solutions
/Chapter2/question1.py
289
4.125
4
print "This program takes Celsius temperature as user \ input and outputs temperature in Fahrenheit" def main(): celsius = input("What is the Celsius temperature?") fahrenheit = (9/5.) * celsius + 32 print "The temperature is", fahrenheit, "degrees Fahrenheit." main()
7bcdb4a3550071c4ff668aa0f7977a1aad65ad16
rohitx/Zelle-Python-Solutions
/Chapter3/question1.py
349
4.25
4
import math print "This program computes the Volume and Surface of a sphere\ for a user-specified radius." def main(): radius = float(raw_input("Please enter a radius: ")) volume = (4/3.) * (math.pi * radius**3) surface = 4 * math.pi * radius**2 print "The Volume is: ", volume print "The S...
5eb290e3566241146e8cbb3aa1a44d9122f170ab
brandontownes/RentSplitter
/RentSplitter/test.py
238
3.765625
4
# start # dictonaries dict = {} dict["1"] = "Brandon" dict["2"] = "Bryan" b = dict["1"] c = dict["2"] print('Hello ' + b + "!") # lists myList = ['Brandon', 'Bryan'] print(myList) person = myList.append('Brennan') print myList[0]
f5a774ded5220fdfdc3402a92e2837e2ccb5a523
PKamonthip/test_project
/som.py
1,358
3.9375
4
def demo1 (): i = 1 while i <= 10: print(i) i += 1 print ('bey') #demo1() def demo_for(): for i in range (1,11): print(i) print ('bye') #demo_for() def sum_input(): n = int(input('enter: ')) total = 0 while n != 0: total += n n = int(input('ent...
08b060ae56667c2003513e395479e12a6de15c39
PKamonthip/test_project
/OOP.py
2,746
3.546875
4
#OOP = Object Oriented Programming from tkinter import * class product: def __init__(self,gui): self.windows = gui self.windows.title('GUI wirh OOP') self.windows.geometry('500x600+900+200') self.windows.resizable(0, 0) #Frame 1 ======== fm1 = LabelFrame(text='Produc...
97d39ea23226befd805b15dedc45fd717c317ee0
PKamonthip/test_project
/DB.py
417
3.90625
4
import sqlite3 con = sqlite3.connect('DB_Test.db') con.cursor() cur = con.cursor() sql = 'SELECT * FROM Tb_Name' cur.execute(sql) #ประมวล DB rows = cur.fetchall() print(rows) for column in rows: print('ID : ', column[0]) print('Name : ', column[1]) print('Addres : ', column[2]) print('Birthday : ', c...
cac78260b79564b2570c1513a1da36ba56abc5f0
chirag1992m/geeky
/HackerRank/ProjectEuler/euler017.py
2,233
3.984375
4
''' Number to Words https://www.hackerrank.com/contests/projecteuler/challenges/euler017 ''' def getTenties(num): return { 10: "Ten", 11: "Eleven", 12: "Twelve", 13: "Thirteen", 14: "Fourteen", 15: "Fifteen", 16: "Sixteen", 17: "Seventee...
30422f03997063a4199f967751c834aae1ca5c8b
chirag1992m/geeky
/HackerRank/ProjectEuler/euler009.py
808
3.75
4
#!/bin/python3 ''' Special Pythagorean Triplet https://www.hackerrank.com/contests/projecteuler/challenges/euler009 ''' import sys ''' Given, a + b + c = N a^2 + b^2 = c^2 a, b, c are integers Solving the three equations give, c = N - a - b b = (N^2 - 2Na)/2(N-a) for b to be integer, the denominator s...
e7970878dd47a0a707eb42ab0a5964723cc9be04
chirag1992m/geeky
/HackerRank/ProjectEuler/euler005.py
836
4.09375
4
#!/bin/python3 ''' Smallest Multiple https://www.hackerrank.com/contests/projecteuler/challenges/euler005 ''' import sys ''' Smallest multiple of numbers from 1 to N would be the multiple of primes from 1 to N using their highest multiplicity < N For eg: LCM of 1 to 10 = 2520 = 2^3 * 3^2 * 5 * 7 ''' #...
85bfdca6805b64b07f414c7db5096eb35f8ec6e7
chirag1992m/geeky
/HackerRank/ProjectEuler/euler006.py
567
3.796875
4
#!/bin/python3 ''' Sum Square Difference https://www.hackerrank.com/contests/projecteuler/challenges/euler006 ''' import sys ''' It asks the following difference: ((\sum_{i=1}^{i=N}{i})^2 - (\sum_{i=1}^{i=N}{i^2})) = (n^2 * (n+1)^2 / 4) - ((n*(n+1)*(2n+1))/6) which reduces to the following get_difference ...
462b1047ab74c8336b5ff87a985213ab65bfdfd8
HoweverC/LeetCode-Python
/LeetCode-941.py
456
3.546875
4
class Solution: def validMountainArray(self, A: 'List[int]') -> 'bool': if len(A) < 3: return False max_num = A.index(max(A)) if (max_num == 0) or (max_num == len(A) - 1): return False for i in range(0,max_num): if (A[i+1] <= A[i]): ...
95a09c78d7237b00fabc3c9b50cfbb85ccb62dd7
DespoinaZografidou/Python_Mini_Projects
/icsd16041_asn2/Exercise2.py
3,922
3.8125
4
#Despoina Zwgrafidou 321/2016041 import os #vrogxos epanalhpshs gia thn epanalhpsh ths diadikasia an thelhsei o xrhsths while True : #vrogxos epanalhpshw se periptwsh pou o xrhsths den eisagei kati gia thn sugkekrimenh erwthsh while True : answer = input('\nChoose one of the following:\n 1)I...
452aa72d6b38bc977bfe1dd48b1cd6f76873dbe6
zhengxiaoyao0716/algorithm-experiment
/question4.py
2,278
3.578125
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ 扑克牌 @author: zhengxiaoyao0716 """ from util import read_inputs, StrValidator CARDS = {str(i): i for i in range(3, 11)} CARDS.update({ "J": 11, "Q": 12, "K": 13, "A": 14, "2": 15, "joker": 16, "JOKER": 17 }) def compare_cards(left, right): """比较两手牌""" ...
56abae18f307490c3ff6495c05662f647e796265
Jasonpangsj/AID2003
/ftp_server.py
1,732
3.59375
4
""" ftp文件服务器 """ from socket import * from threading import Thread import os from time import sleep HOST = "0.0.0.0" PORT = 9999 ADDR = (HOST, PORT) FTP = "/home/tarena/ftp" class FtpServer(Thread): def __init__(self, connfd): self.connfd = connfd super().__init__() def do_list(self): ...
a73e162713d5c09b0e70286b384af2b8b61df19c
vincent-bataille/formation
/python_fr/exo/script.py
149
3.578125
4
print('les chaines de caracteres :') print("Hello world") numero=1_000_000 print(numero) nombre = input("entrez un nombre : ") print(nombre) exit()
ca20faf4e6b8365bcbffe5f3fe94ce0c1d07c239
PeterParkSW/User-Logins
/UserLogins.py
1,525
4.4375
4
#dictionary containing paired usernames and passwords that have been created #keys are usernames, values are passwords credentials = {} #asks user for a new username and password to sign up and put into credentials dictionary def signup(): new_user = input('Please enter a username you would like to use: ') whi...
4f6a3173546feb61e2a7d3726e2ffc3337915e36
ecoArk/python_code
/exercise_python/hangman.py
1,120
4.03125
4
# Let's try making a hangman game # random module is used for making the question import random # sample question city = ['semarang', 'jakarta', 'bandung', 'surabaya', 'malang'] chance = 0 tried_answer = [] # Establish the framework of the answer answer = city[random.randint(0, len(city)-1)] disp_question = list(ans...
29b34b47dbda03d84d4f158bd49992dc274eac5f
smoross/hw3
/madlibhw3.py
1,617
3.546875
4
print('Samantha Moross''\n''Project 3''\n''Section 002: Wednesday 5:30-6:30 pm''\n''Madlib') print('-----------') # A) Madlib: madlibhw3.py import nltk import random from nltk.corpus import gutenberg from nltk import word_tokenize, sent_tokenize debug = False if debug: print ("Getting information from text2...\n...
a837fe91bca44780fab2b29912f0df2cfc5e7d49
Alexanderklau/Amusing_python
/Algorithm/list.py
395
3.765625
4
#coding: utf-8 # 最基础的遍历无序列表的查找算法 # 时间复杂度O(n) def sequential_search(lis, key): length = len(lis) for i in range(length): if lis[i] == key: return i else: return False if __name__ == '__main__': LIST = [1, 5, 8, 123, 22, 54, 7, 99, 300, 222] result = sequential_s...
25bda023de18ab2e2ab552681c653e95136cfdcb
Alexanderklau/Amusing_python
/Algorithm/Sort/insert_sort.py
386
3.984375
4
#coding: utf-8 # 插入排序 def insert_sort(lists): count = len(lists) #统计总数 for i in range(1, count): #遍历 key = lists[i] j = i - 1 while j >= 0: if lists[j] > key: lists[j + 1] = lists[j] lists[j] = key j -= 1 return lists list...
e46dbd6eaf7c59323ff6bf49adce89ac675cf6b6
Alexanderklau/Amusing_python
/Thread_work/Thread_Work/queue_con_model.py
648
3.578125
4
# coding: utf-8 __author__ = 'Yemilice_lau' import threading import time from queue import Queue queue = Queue(20) # 生产者 def Producer(): i = 0 print("开始线程") while True: i = i + 1 print("生产数据", i, "现有数据", queue.qsize()) time.sleep(1) queue.put(i) # 消费者 def Consumer(m): ...
d5441ca9d8a467482c1341852a04c893850c10b5
KhoobBabe/math-expression-calculator
/mathmatical expression calculator.py
1,629
4.1875
4
import warnings print('Enter a mathematical expression to view its result') #we put a while to cotinously prompt the yser to input expressions cond = True while cond is True: #this ignores other warnings warnings.simplefilter('ignore') #input is taken here a = input("\nEnter a mathematical...
84655e7f783e647b97e03d15ac3ad354b83ee685
MakarVS/GeekBrains_Algorithms_Python
/Lesson_2/Check/Lesson2/Les2_Task1.py
1,825
4.03125
4
#1. Написать программу, которая будет складывать, вычитать, умножать или делить два числа. #Числа и знак операции вводятся пользователем. После выполнения вычисления программа не завершается, #а запрашивает новые данные для вычислений. #Завершение программы должно выполняться при вводе символа '0' в качестве знака ...
66d60d0817f0a8d610c9176e6a3230d639cba471
MakarVS/GeekBrains_Algorithms_Python
/Lesson_3/les_3_task_6.py
1,071
3.75
4
# Задача № 6. # В одномерном массиве найти сумму элементов, находящихся между минимальным и максимальным элементами. # Сами минимальный и максимальный элементы в сумму не включать. import random lst = [random.randint(-10, 10) for i in range(1, 10)] print(f'Исходные массив {lst}') ind_mn = 0 ind_mx = len(lst) - 1 for...
f146be01d63dfa0fece7ec7ba65f6741e58e4224
MakarVS/GeekBrains_Algorithms_Python
/Lesson_1/Check/Алгоритмы и структуры данных на Python_Введение/zadanie4.py
622
3.90625
4
# Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят, и сколько между ними находится букв. bukvi=('abcdefghijklmnopqrstuvwxyz') a=input('Введите первую букву: ') b=input('Введите вторую букву: ') granica_1=bukvi.find(a) granica_2=bukvi.find(b) dlina=granica_2-granica_1-1 print('Буква {} имеет...
8f5a4ec5a011c99de830816d793ee481425a6bcb
MakarVS/GeekBrains_Algorithms_Python
/Lesson_1/Check/phyton 1/zadanie1.py
402
3.796875
4
nun = input("введите число 5 или 6: ") a = 5 print("%d = %s" % (a, bin(a))) b = 6 print("%d = %s" % (b, bin(b))) print("%d & %d = %d (%s)" % (a, b, a & b, bin(a & b))) print("%d | %d = %d (%s)" % (a, b, a | b, bin(a | b))) print("%d ^ %d = %d (%s)" % (a, b, a ^ b, bin(a ^ b))) print("%d << 2 = %d (%s)" % (b, b << 2, b...
09b833fd5555dc8c04493f650146e64b1c03dcd0
MakarVS/GeekBrains_Algorithms_Python
/Lesson_7/Check/urok7/7-3.py
1,174
3.78125
4
from random import randint, choice # Поиск медианы в списке m = 5 n = 2 * m + 1 A = [randint(0, 100) for i in range(n)] print('Исходный массив: ', A) # Можно было бы и так: # A.sort() # median = A[n // 2] # print(A) # print(median) # [19, 5, 22, 83, 48, 48, 79, 15, 71, 0, 6] # [0, 5, 6, 15, 19, 22, 48, 48, 71, 79, 8...
8472722c41a3571c58942a49b9262663ba4c3095
MakarVS/GeekBrains_Algorithms_Python
/Lesson_3/Check/Lesson3/zadanie3.py
476
4.03125
4
# В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. # massiv=[1,2,0,5,3,21,3] import random massiv = random.sample(range(1, 100), 10) print(massiv) x=0 k=99999999 for i in massiv: if i>x: x=i if i<k: k=i print(k,x) min=massiv.index(k) max=massiv.index(x) print(max,min) massiv...
f58fce209324c621cbeebac88493ef6a9589e448
MakarVS/GeekBrains_Algorithms_Python
/Lesson_7/les_7_task_2.py
1,695
4.28125
4
""" Задача № 2. Отсортируйте по возрастанию методом слияния одномерный вещественный массив, заданный случайными числами на промежутке [0; 50). Выведите на экран исходный и отсортированный массивы. """ from random import uniform n = 10 array = [uniform(0, 50) for _ in range(n)] print(f'Изначальный массив - {array}') ...
59fd535df22a2c9d0b42881dbc0363ef85e835f1
MakarVS/GeekBrains_Algorithms_Python
/Lesson_7/les_7_task_3.py
2,412
3.96875
4
""" Задача № 3. Массив размером 2m + 1, где m — натуральное число, заполнен случайным образом. Найдите в массиве медиану. Медианой называется элемент ряда, делящий его на две равные части: в одной находятся элементы, которые не меньше медианы, в другой — не больше медианы. Примечание: задачу можно решить без сортировки...
e75b3d20c59f19ddac7f5b45e9ab333c4ab571ca
MakarVS/GeekBrains_Algorithms_Python
/Lesson_1/Check/geekbrains dz/geekbrains dz/task_2.py
427
3.875
4
x1 = float(input('введите абсциссу 1 точки ')) y1 = float(input('введите ординату 1 точки ')) print() x2 = float(input('введите абсциссу 2 точки ')) y2 = float(input('введите ординату 2 точки ')) k = (y1 - y2) / (x1 - x2) b = y2 - k * x2 print() print('уравнение проходящее через эти 2 точки \n', f'y = {k}x + {b}')
91c31541149c611200972360d1fe701328937e12
MakarVS/GeekBrains_Algorithms_Python
/Lesson_2/Check/Lesson2/Les2_Task3.py
436
4.125
4
#3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. #Например, если введено число 3486, надо вывести 6843. num = int(input("Введите число: ")) num2 = 0 while True: num2 = num2 * 10 + num % 10 num //= 10 if num == 0: break print(f"{num2}")
2c521ccdc9bdf8d17135c8c7efadddf3b196a025
MakarVS/GeekBrains_Algorithms_Python
/Lesson_3/Check/hw_nekrasov_lesson_3/les_3_task_5_nek.py
1,356
3.6875
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 4 12:56:46 2020 @author: Nekad """ # ============================================================================= # 5. В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и позицию в массиве. # =============================================...
0b811022ee2e0b9c6c51a13b11e6c8d7e272fad3
neekoleung/marvel-new-avengers-prediction
/chart_skill.py
4,983
3.59375
4
""" Name of file: chart_skill Author: Puxing Zhao Purpose: Display the information about the number of heroes in each range of the skills Module imports it: main """ import matplotlib.pyplot as plt import pandas as pd import numpy as np #create a function chart_skills which will be used in the main method...
7585a5b7adbe67c4e986fae6ce9aa40944d8f0fe
neekoleung/marvel-new-avengers-prediction
/Prediction_appearances_and_skills.py
4,369
3.90625
4
""" Name of file: Prediction_appearances_and_skills Author: Puxing Zhao Purpose: Display the information about the predictions of heroes based on the entrophy of appearances and skills Module imports it: main Module it imports: Weight """ import pandas as pd import Weight #create a function Prediction_appearances_an...
da24699b3f07553c8351b8679c4efe47d54f7ee9
jakehowlett93/small-programs
/dice_rolling_simulator.py
344
3.90625
4
import random while True: roll_dice = input("would you like to roll the dice? (y/n): ").lower() while roll_dice != 'y' and roll_dice != 'n': roll_dice = input("please enter y or n: ") if roll_dice == 'y': print(random.randrange(1, 7)) elif roll_dice == 'n': print(...
4fee84d6ed529d139f2d9617a8e6ada136075556
prateek951/OpenCVforComputerVision
/matplotlib/lineplot.py
393
3.9375
4
from matplotlib import pyplot as plt # Function to plot a line x = [1,2,3] y = [5,7,4] x2 = [1,2,3] y2 = [10,14,12] plt.plot(x,y,label='First Line') plt.plot(x2,y2,label='Second Line') # Legends,titles and plots in matplotlib # which is quite similiar to matlab plt.xlabel('x') plt.ylabel('y') plt.title('Interest...
355ea39dfda94de5d644fb0820241d32ef81efaf
prateek951/OpenCVforComputerVision
/imageopera.py
594
3.625
4
import numpy as np import cv2 # Reading the image and store it in a variable img = cv2.imread('watch.jpg',cv2.IMREAD_COLOR) # img[55,55] = [255,255,255] # px = img[55,55] # print(px) # ROI of the image Region of interest for the image # roi = img[100:150,100:150] # print(roi) # Here we have co...
b77885895b2078306be6934e966d70e41a1b32ce
prateek951/OpenCVforComputerVision
/MiniProjectsinCV/SIFT.py
678
3.515625
4
# USING SIFT,SURF,FAST,BRIEF AND ORB # Create a detector # Input image into the detector # Obtain the keypoints # Draw the keypoints import cv2 import numpy as np # Read and decode the input image image = cv2.imread('input.jpg') # Convert the image to the gray scale gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # In...
8e3fed0529f4d572d8847fab94465394be3b73cb
jbelo-pro/Tic-Tac-Toe
/Problems/Odd numbers/task.py
63
3.5
4
text = input() print([int(x) for x in text if int(x) % 2 != 0])
e4edc824a7ca7d57fce129b57816a97908269b76
brianvs18/Reto_AlgoritmosPython
/Ejercicio4.py
536
4.09375
4
#Algoritmo que lea tres números distintos y nos diga cual de ellos es el mayor (recuerda usar la estructura condicional Si y los operadores lógicos). num1 = 0 num2 = 0 num3 = 0 num1 = int(input("Ingrese numero 1: ")) num2 = int(input("Ingrese numero 2: ")) num3 = int(input("Ingrese numero 3: ")) if num1 > num2 and n...
71feca0b51d97482575a3e08a5d2a830d264c584
brianvs18/Reto_AlgoritmosPython
/Ejercicio7.py
526
4.0625
4
# Un colegio desea saber qué porcentaje de niños y qué porcentaje de niñas # hay en el curso actual. Diseñar un algoritmo para este propósito # (recuerda que para calcular el porcentaje puedes hacer una regla de 3) ninos = 0 ninas = 0 ninos = int(input("Ingrese la cantidad de niños: ")) ninas = int(input("Ingrese la ...
2372f9f18512400671ab59b2d170c00826a081ef
zwtgyh/pycharm
/python cookbook/1.数据结构和算法/1.py
944
3.625
4
def phone_number_out (record): first, second, *last = record print(*last) records = ('Dave', '@email.com', '13814536225', '18844470055') phone_number_out (records) ######## import heapq portfolio = [ {'name':'IBM', 'shares':100, 'price':91.1}, {'name':'AAPL', 'shares':50, 'price':543.22}, {'name':'F...
3f51151fdade169f8efdf8d42533c86081373fbe
tlmakinen/experimental_physics
/homework_1/simpleGraph.py
909
3.890625
4
import numpy import matplotlib.pyplot as plt # enter the data as python lists x = [ 0., 10., 20., 30., 40. ] force = [ 10., 25., 35., 60., 80.] #create a figure and set limits on the axes plt.figure(1) plt.xlim(0.,50.) plt.ylim(0.,100.) # plot the force points vs. the x points # 'bo' ==> use blue circle markers plt...
b436e3b4bdcf9e626ab657f3c8b6acf493542cc0
BenPoser/HackerRank
/Algorithms/MinMax Sum.py
338
3.71875
4
#!/bin/python3 import math import os import random import re import sys # Complete the miniMaxSum function below. def miniMaxSum(arr): arr.sort() total = sum(arr) print((total - arr[-1]), (total - arr[0])) if __name__ == '__main__': arr = list(map(int, input().rstrip().split())) ...
a18bd9e9f15841316a0cd1e02b376ff819505dfa
BenPoser/HackerRank
/set union.py
1,211
3.796875
4
# Task # The students of District College have subscriptions to English and French newspapers. Some students have subscribed # only to English, some have subscribed to only French and some have subscribed to both newspapers. # # You are given two sets of student roll numbers. One set has subscribed to the English n...
db04e61ceb31446d309df381f493541f8b4d3fa0
BenPoser/HackerRank
/No Idea!.py
790
3.65625
4
# You like all the integers in set A and dislike all the integers in set B. Your initial happiness is 0. # For each i integer in the array you like add 1 to your happiness. If you don't like add -1 to your happiness. # Input Format # # The first line contains integers n and m separated by a space. # The second ...
3cc2b1f62740a2e10930f8db87cc1d98c0c1266b
XMirtX/Implantacion-de-aplicaciones-web
/ut2/a2/Programa3.py
450
3.8125
4
import sys nota = float(sys.argv[1]) if nota >= 0 and nota <= 10: if nota < 5: print("Suspenso") if nota == 5: print("Aprovado") if 5 + 1 <= nota < 6 + 1: print("Bien") if 7 <= nota < 8: print("Notable") if nota == 8: print("Notable_alto") if nota == 9: ...