blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a0cecb7606f31bd00c4b94dee8ad3754f9b36712
Paalar/TDT4110
/Øving 3/georekk.py
383
3.671875
4
n = float(input("N")) r = 0.5 r0 = 0 while n >= 0: r0 += r**n n -= 1 print ("Summen av rekken er ", r0) tol = float(input("\nen toleranseverdi")) r0 = 0 n = 0 r = 1/2 while r0 <= (1/(1-r))-tol: r0 += r**n n += 1 print ("For å være innenfor toleranseverdien", tol, "kjørte løkken", n, "ganger.") print ...
6071e4d668dca5b7283aa4ebe0f1e80fac1ef276
alortimor/python_tricks
/numbering/calculate_item_price.py
870
4.09375
4
#!/usr/bin/python3 """ Working with currency required the Decimal class. Do not mix Decimal and float. vat_rate = Decimal('1.25') item_price= Decimal('9.99') total = vat_rate * item_price Quantize decimal numbers using a cents object: cent = Decimal('0.01') total = total.quantize(cent) The decimal module can then be ...
127fda00955256f2885ca355936e21287a1fab66
Prashant-mahajan/Python-Codes
/Leetcode/289gameOfLife.py
1,437
3.9375
4
class Solution: def gameOfLife(self, board): """ :type board: List[List[int]] :rtype: void Do not return anything, modify board in-place instead. """ # To work in place instead of creating an separate matrix, assign 1->0 as 2 and 0->1 as 3 length, breadth = len(board...
23a48ba8225bcabf71c489536ce55eb75ceddc08
mouhtasi/LeetCode-solutions
/020.py
1,004
3.875
4
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ valid = True left_brackets = ['(', '{', '['] matching_brackets = {'(': ')', '{': '}', '[': ']'} opening_brackets = [] for bracket in s: if bracket i...
92187dd06242299bc9919060f353270e22df2f4d
adiboy6/python-practice
/control_flow.py
346
4.125
4
""" range(stop): Starts from 0 to stop - 1 range(start,stop[,step]): Starts from start to stop - 1 with an incremental step(positive) or decremental step(negative) it behaves like a list but it isn't """ r = range(0, 20, 2) print(11 in r) print(10 in r) print(r[5]) # shows the first 5 el...
668fc4b0be62f68eb54f44a3167a03154b4cf87f
win224/python
/shopping.py
1,267
3.890625
4
#!/usr/bin/python production_list = [ ('iphone', 8000), ('mac pro', 9800), ('coffee',30), ('roy',2000) ] shooping_list = [] salary = raw_input("Input your salary:") if salary.isdigit(): salary = int(salary) while True: for index, item in enumerate(production_list): print(in...
4a4b924d4e23b3365acf10d765ead4a7cf81b38c
mbhushan/algods-python
/hr_designer_pdf_viewer.py
473
3.828125
4
#!/bin/python import sys """ https://www.hackerrank.com/challenges/designer-pdf-viewer """ def main(): h = map(int, raw_input().strip().split(' ')) word = raw_input().strip() alphabets = "abcdefghijklmnopqrstuvwxyz" max_ht = -1 * sys.maxint for s in word: index = alphabets.index(s) ...
9a6092fe4c58a40ca9bcdc182949004891af3101
shilihui1/Python_codes
/second_largest.py
454
3.765625
4
# O(nlogn) class solution: def second_largest(a): a_sorted = sorted(a) max_value = max(a) for key, value in enumerate(a): if value == max_value: a_sorted.pop() return max(a_sorted) print(solution.second_largest([2, 3, 6, 6, 5])) # O(n) class solution: ...
1b3bd9d77ba8f346e97b6c7952b0cf5308fcb181
quintasluiz/devaria-python
/exercicios-python/ex057.py
473
4.03125
4
#Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores 'M' ou 'F'. # Caso esteja errado, peça a digitação novamente até ter um valor correto. sexo = str(input('Qual o seu sexo? [M/F]: ')).strip().upper()[0] while sexo not in 'MmFf' and sexo != 'homem' and sexo != 'mulher': sexo = str(input('Dados...
ce08fd228ce3f353e0a13e09da7f1285740f3907
WialmySales/redes
/REDE/camadas.py
4,055
3.8125
4
#!/usr/bin/python3 # coding: utf-8 """ Classes das camadas TCP/IP """ class CdAplicacao(): def __init__(self, camada): self.camada = camada # print("Camada TCP/IP: Aplicação") def desencapsular(self): return self.camada def responsabilidade(self): return "Responsável pel...
f58d5d2e54c5363d63644b9aa6198b6107958b43
taavirepan/adventofcode2020
/6/task1.py
307
3.734375
4
ret = 0 yes = set() for line in open("input.txt"): line = line.strip() if line == "": # Note that for this data, I added one more line at the end of input.txt, so # that this if is always entered at the end of the file. print(yes) ret += len(yes) yes = set() else: yes |= set(line) print(ret)
fe026a813e7693c86efce7cb22cd4009f749a87e
karthik1017/mca
/python/python_assignment4/python_4/pro4.py
356
4.34375
4
# 4. Read a string and a character and display the frequency of its occurrence in the string. str1 = str(input('enter a string to check the freuency: ')) def frequency(str1): di = {} for i in str1: if i in di: di[i] += 1 else : di[i] = 1 return di print('the freque...
08b5d91f0fb7497157a4e598f7ed435c43ed4d56
apalaciosc/python_quantum
/clase_06/coordenada.py
880
3.96875
4
class Coordenada: def __init__(self, x=0, y=0): self.__x = x self.__y = y @property def x(self): return self.__x @x.setter def x(self, coor_x): if coor_x >= 0: self.__x = coor_x else: raise ValueError('No es una coordenada válida.') @property def y(self): return self.__y @y.setter def y(s...
36455270793a7c7541a0827dc5d1e776649b361f
ziqingW/pythonPlayground
/leetcode/linkedlist/linkedListRemoveFromEnd.py
2,401
3.796875
4
# Given a linked list, remove the n-th node from the end of list and return its head. # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head, n): """ :type head: ListNode ...
1ec546b2bdb7d32fe56f99cf9c28e307ef84ba20
honghyk/algorithm_study
/217. Contains Duplicate.py
257
3.546875
4
from typing import List # Array, Hash Table class Solution: def containsDuplicate(self, nums: List[int]) -> bool: numsSet = set(nums) if len(nums) != len(numsSet): return True else: return False
993f13e20108d46a3d3059f0edfbe32dfec22aa6
darkxaze/HarvardX-PH526x-EdX
/Misc/language_ipo.py
3,417
4.03125
4
text = "This is my test text. We're keeping this text short to keep things manageable." def count_words(text): text = text.lower() skips = [".", ",",";",":","'",'"'] for ch in skips: text = text.replace(ch,"") word_counts = {} for word in text.split(" "): # known word if wo...
870b4579aef61368de7dc41e65ca2dde9a586ac5
gabriellee/SoftwareDesign
/hw2/fermat.py
518
4.0625
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 2 19:30:16 2014 @author: gabrielle """ print "Please enter the value for a" a = int(raw_input()) print "Please enter the value for b" b = int(raw_input()) print "Please enter the value for c" c = int(raw_input()) print "Please enter the value for n" n = int(raw_input()) ...
266afd81fab48d9d7de7217497f1f06010858388
NasirAwed/IN1000
/oblig4/regnelokke.py
570
3.828125
4
# Et program for å legge tall i en liste og gjøre forskjellige oprasjoner på dem T=True liste = [] while T: tall= int(input("Tast inn et tall (0 for å avslutte): ")) if tall == 0: T = False else: liste.append(tall) for i in liste: print(i) minsum=0 for x in liste: minsum = minsum +...
5c5719c87de1694c6915bffdc9af76b955adce84
joeyzhao2018/TaggingCodingPractices_InterviewProblems
/src/dynamicProgramming/knapsack/target_sum.py
2,898
4.0625
4
description="""You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol. Find out how many ways to assign symbols to make sum of integers equal to target S. Example 1: Input: nums is [1, 1, 1...
c02815fd17919aabe0d0d79254ed3863c51a8821
lsb530/Algorithm-Python
/이것이코딩테스트다/정렬/선택정렬.py
563
3.6875
4
# 선택정렬, 시간 복잡도 O(N^2) array = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8] for i in range(len(array)): min_index = i # 가장 작은 원소의 인덱스 for j in range(i + 1, len(array)): if array[min_index] > array[j]: min_index = j array[i], array[min_index] = array[min_index], array[i] # 스와프 print(array) # 파이썬에서의...
aa20c46e76787d35ff18261c030c09461b02f121
AdamZhouSE/pythonHomework
/Code/CodeRecords/2387/60835/273945.py
614
3.546875
4
n = input().split(' ') tem = input().split(' ') group = [] for x in tem: group.append(int(x)) def sort(mark,group,start,end): new = [] for x in range(start): new.append(group[x]) tem = [] for x in range(start,end + 1): tem.append(group[x]) if mark == 1: tem.sort(reverse =...
447a4938dc66bd68dbee97f20b5cfe19f04770fe
ladroff/python_hw_3
/8.py
228
3.71875
4
x = int(input("Введите год :")) y, z, a = x % 4, x % 100, x % 400 if y == 0 and z != 0 or a == 0: print(x, "Этот год - высокосный") else: print(x, "Этот год - не высокосный")
9f59b43e4b12e8c4fdc3059395a248f0691e1634
PPJ-Grupa/PPJ
/Lab4/Lines.py
4,518
3.625
4
from helpers import * from Expr import Expr def pprint(stri): return print(stri) class Lines: def __init__(self, lines): self._lines = lines self._iter = 0 self.terminate = False self.result = "" """Check whether iter is out of bounds""" def iter_outside(self): return self._iter < 0 or s...
16fa8a5480a84b7393fd5b4ea53ebbda95a1235c
Mayurg6832/HackerRank-Problem-solving
/itertools.product().py
168
3.53125
4
from itertools import product lst1=list(map(int,input().split())) lst2=list(map(int,input().split())) lst=list(product(lst1,lst2)) for i in lst: print(i,end=" ")
6328db7a33c40c2fde620fb4a651fbb1528ab3b1
Arrowarcher/Python_Concise_Handbook
/15-高级特性之迭代.py
1,630
3.765625
4
##1********python的迭代不仅可用在list或tuple,还可以作用在其他可迭代对象上 #dict迭代: d = {'a':1,'b':2,'c':3} for key in d: print(key) #注意:dict的储存不是按照list顺序,所以结果顺序可能不一样 # dict默认迭代key #迭代dict的value: for value in d.values(): print(value) #同时 for k,v in d.items(): print(k,v) #字符串的迭代: for ch in 'ABC': print(c...
bd6f3ba70ab8527bc64b06ae76ae17c60edfae84
shishir7654/Python_program-basic
/inheritance4.py
307
3.703125
4
class Calculation1: def sum(self,a,b): return a+b; class Calculation2: def mul(self, a,b): return a*b; class Derived(Calculation1,Calculation2): def div(self,a,b): return a/b; d = Derived() print(d.sum(10,20)) print(d.mul(10,20)) print(d.div(10,20))
8e581368f8d1dc05b5dc01c8e2e0eb1e0c4f081c
Broast42/Data-Structures
/lru_cache/lru_cache.py
3,083
3.859375
4
from doubly_linked_list import DoublyLinkedList class LRUCache: """ Our LRUCache class keeps track of the max number of nodes it can hold, the current number of nodes it is holding, a doubly- linked list that holds the key-value entries in the correct order, as well as a storage dict that provides ...
f6382d1bb9f0ffafe700d432014f7966870e10a3
bradandre/Python-Projects
/College/Homework Programs/Triangle Hypotenuse.py
1,250
3.9375
4
import tkinter as tk from tkinter import messagebox import math class Application(tk.Tk): def __init__(self, master=None): tk.Tk.__init__(self, master) self.title("Triangle Hypotenuse Calculator") self.create() def create(self): self.aLabel = tk.Label(self, text="A Value:").gri...
c3b667dad0e992f5005f34fa2bc9bdd13e44ed39
SamirRuiz20/MisPracticas
/estructura_de_datos/list_circular_simple.py
4,570
3.859375
4
class Nodo : def __init__(self, data) : self.data = data self.next = None self.values = [ ] class ListCircSimple : def __init__(self) : self.start = None self.end = None self.size = 0 def run(self) : aux = self.start while aux : print(aux.da...
573420db0d9000aac1e31e6b4eb2b3106fd494fe
Weless/leetcode
/python/general/1295. 统计位数为偶数的数字.py
286
3.65625
4
from typing import List class Solution: def findNumbers(self, nums: List[int]) -> int: count =0 for num in nums: if len(str(num)) % 2 == 0: count +=1 return count s = Solution() nums = [12,324,2,6,7896] print(s.findNumbers(nums))
f550fcae87c248207a981aad223fe2aee179a86f
MasumTech/URI-Online-Judge-Solution-in-Python
/URI-1041.py
512
3.59375
4
r1 = input().split(" ") a, b= r1 if float(a)>float(0.0) and float(b)>float(0.0): print('Q1') elif float(a)<float(0.0) and float(b)>float(0.0): print('Q2') elif float(a)<float(0.0) and float(b)<float(0.0): print('Q3') elif float(a)>float(0.0) and float(b)<float(0.0): print('Q4') elif float(a)==float(0.0...
5ce89e3e78462e57bb63829f35fd8375ea1102e6
rohit-kumar6/DailyCode
/Day2/optimise_day2_5.py
340
3.578125
4
nums = [1,2,3,4,5] n = len(nums) left, right, result = [1] * n, [1] * n, [1] * n for i in range(1, len(nums)): left[i] = nums[i - 1] * left[i - 1] for i in range(len(nums) - 2, -1, -1): right[i] = right[i + 1] * nums[i + 1] print(left) print(right) for i in range(0, len(nums)): result[i] = left[i] * rig...
d314ca9414455a1fd7d3370ed986a9786ae1f722
cci9/Data_Structure
/BubbleSort.py
377
4.0625
4
def bubble_sort(nums): for i in range(len(nums) - 1): for j in range(0, len(nums) - 1 - i, 1): if nums[j] > nums[j + 1]: swap(nums, j, j + 1) return nums def swap(nums, i, j): temp = nums[i] nums[i] = nums[j] nums[j] = temp if __name__ == '__main__': ...
82820538f366b9f6a0deee78badb5834b30c165e
Pranav-7/Python-programming
/control-flow.py
2,049
4.1875
4
''' def findArea(r): PI = 3.142 return PI * (r*r); # Driver method print("Area is %.6f" % findArea(5)); ''' ''' start = 11 end = 25 for i in range(start, end+1): if i>1: for j in range(2,i): if(i % j==0): break else: print(i) ''' ''' num = 407 if num > 1: for ...
96616a9e1a4a3d050e720708b438ebca26a89024
Torhque/Python
/Stock Portfolio Ureta, Julio.py
3,695
4.1875
4
## Julio Ureta CSC102 ## Create Names dictionary. Names = {} ####Names["GM"] = "General Motors" ## Create Prices dictionary. Prices = {} ## Create Exposure dictionary. Exposure = {} ## Asks the user for a Stock Symbol and Name pairing then adds it to the Names dictionary. def AddName(): stock_...
a4d9406bed3f8fa9b03b84dc53ce8ec41a07929d
suhailshergill/pystoch
/testing/transform/testfiles/itertools.py
387
3.796875
4
# taken from http://wiki.python.org/moin/SimplePrograms import itertools lines = ''' This is the first paragraph. This is the second. '''.splitlines() # Use itertools.groupby and bool to return groups of # consecutive lines that either have content or don't. result = [] for has_chars, frags in itertools.groupby(line...
be20ed917cfeed511dfbb5a06e4af64c77161cf8
angelicahs/basic-python-b4-c
/list.py
264
4
4
mylist = [4,5.3, "appple"] # 0 1 2 # mylist.append(1) # mylist.append(2) # mylist.append(3) # print(mylist) # print(mylist[0]) # print(mylist[5]) # print(mylist[0:4]) print(mylist[0]) print(mylist[1]) print(mylist[2]) for x in mylist: print(x)
55def0298e0d7156b3d9d54f9297e47e98b887e6
Ricky-Castro/python
/Aula4/Aula4.py
343
3.890625
4
""" Tipos de dados str = string = texto 'assim' ou "assim" int = inteiro = números inteiros (123456) float = real/ponto flutuante = 10.0 1.5 bool = booleano/lógico = verdadeiro ou falso (true or false) ex: 10 == 10 """ # print('L' == 'n', type('L' == 'L')) print(type('Henrique'), bool('Henrique')) print('sou maior...
af271aa1cb0c90c75de5de18ef2630acc3c1b621
Batievskiy/My-CS50-course
/notes/lecture 7/lecture7_notes1.py
765
4.28125
4
# Cleaning import csv # let's open a file in `read` mode and create a variable called `file` with open("Favorite TV Shows - Form Responses 1.csv", "r") as file: # crete a reader # and it's gonna be the return value of calling csv.reader on that file reader = csv.reader(file) # we gonna skip the firs...
c52f803ef365acf4d408f47256a1089c6b09ecd7
ksv2017/pylessons
/urok1_functions.py
603
4.0625
4
import random def list_of_randomly_generated_ints(range): """ This function generates a list of random numbers between 1 and 20 """ list = [] i = 0 while i < range: i += 1 list.append(random.randint(1,20)) return list def convert_celcius_into_farenheit(celcius): """ This func...
621ed63e83e1eca03ac21cfa81c21b29b21f6911
Asunqingwen/LeetCode
/medium/Maximum Width of Binary Tree.py
3,498
4.3125
4
# -*- coding: utf-8 -*- # @Time : 2019/8/23 0023 17:00 # @Author : 没有蜡笔的小新 # @E-mail : sqw123az@sina.com # @FileName: Maximum Width of Binary Tree.py # @Software: PyCharm # @Blog :https://blog.csdn.net/Asunqingwen # @GitHub :https://github.com/Asunqingwen """ Given a binary tree, write a function to get the m...
917e40d7b89f6dc712676c0dc57ef09d6f7e2f4e
erikkaueusp/Python-scripts
/testemontecarlo.py
887
4.09375
4
from math import exp,sqrt from random import random # Parâmetros de integração N = 10**5 # Número de pontos a utilizar para a integração # Definição da função cujo valor médio será calculado. # Note que aqui se trata da função de integração dividida por w(x)=x**(-1/2) def f(x): return 1/(x**(1/2)*(...
7c5d1c8ce43326f651eff4d611203f6a7b578ab6
alaktionov-hub/python_study
/OOP_1_at_class/task3.py
955
3.640625
4
#!/usr/bin/env python3 class Element: def __init__(self, t_isp, t_pl): self.t_isp = t_isp self.t_pl = t_pl def condition(self, temp, gr): if gr == 'K' or gr == 'k': t = temp - 273 elif gr == 'C' or gr == 'c': t = temp else: print('Un...
a5c086c7a8e8a7ee2493359af56d500244d46070
Kargreat/InterviewKickstart
/timed_tests/target_sum.py
343
3.90625
4
n = 3 k = 6 array = [2, 4, 8] def check_if_sum_possible(arr, k): partial_sum = 0 return target_sum(arr, k, len(arr), partial_sum) def target_sum(arr, k, n, partial_sum): if len(arr) == 0 and partial_sum == k: return True else: return 1 if __name__ == '__main__': print(check_if_...
ee7c4198bf36b9567c6f45d09cc067d2339cb949
baxter1707/CoffeeOrderSystem
/Review/Week 3 Review/smallestNumber.py
138
3.84375
4
numbers = [12,15,1,45,45,90,62,34,5] largest = 100 for small in numbers: if small < largest: small = largest print(largest)
11cd3cbbee052269bbcdc7c1808cea681ddf9866
kalilinukx/test_for_desktop
/hello_world/example.py
165
3.890625
4
x = int(input("Enter any number : ")) s = 0 for i in range(x + 1): s += i # print(i) for j in range(i): s = s + j print("sum is ", s)
3027dd2a53f831b820d8116db2914a4ba528aa78
sareen279/Data-Structures-and-Algorithms
/Hard/Median_Sorted_Arrays.py
736
4
4
#Median of Two sorted arrays #Given two sorted arrays arr1[] and arr2[] of sizes n and n2 respectively. #The task is to find the median of the two arrays when they get merged. arr1 = [1,2,3,4] arr2 = [11,12,13,14] n = len(arr1) n2 = len(arr2) if (n + n2) % 2 == 0: iseven = True else: iseven = False n3 = ((n +...
650085697adb8cb8aebe0cc2809e655f14e8af8b
zuqqhi2/my-leetcode-answers
/48-Rotate-Image.py
1,806
3.671875
4
class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ # Corner case if len(matrix) == 0: return None if len(matrix) == 1: return None start_y = 0 end_...
f0a29160007b713cf7955894c97b94c3598fe07a
shavone328/100-Days-of-Code
/Beginner Projects/Rock Paper Scissors.py
2,130
4.15625
4
import random # Choice images rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) _________...
ddcfcffc26cfb0ed113894481467e335a7ac5022
rdobr/Home-work
/HW1/HW_1.py
362
3.703125
4
#task1 a=int(input('Enter a= ')) b=int(input('Enter b= ')) print((a+b), (a-b), (a*b), (a/b)) #task2 name=input('What is your name? ') age=input('How old are you? ') address=input('Where do you live? ') print('Hello ', name) print('Your age is ', age) print('You live in ', address) #task3 from PIL import Image image =...
30840a37629ffd4c1f9d2c88b0476b5a9042c5d8
AnuarTB/miscellaneous
/BPlusTree/classes.py
12,906
3.90625
4
""" classes.py Implements Node, BPlustree and Interface """ import re import sys import collections def split_list(arr, divider): return arr[:divider], arr[divider:] """Finds position of the key in the sorted array arr Args: key: a variable of the same type as elements of array """ def find_pos(arr, key): ...
f48e57bdf92176ae761fc77ba946daa8f882a567
Matheus-SS/Python
/Função/Ex-funcoes/ex11.py
220
3.890625
4
# Escreva um função que some todos os # números contidos numa lista. lista = [1,2,3,4,5] def func(*lista): num = 0 for i in range(len(lista)): num+=lista[i] i+=1 print(num) func(*lista)
a7590071afc9707ec565b17f719eb6f82876c1ce
BodaleDenis/Codewars-challenges
/pangram.py
995
4.1875
4
""" A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence "The quick brown fox jumps over the lazy dog" is a pangram, because it uses the letters A-Z at least once (case is irrelevant). Given a string, detect whether or not it is a pangram. Return True if ...
58c7527644600c3a127b3186f233df2660292514
green-fox-academy/Kucika14
/week-02/day-01/cuboid.py
358
4.09375
4
# Write a program that stores 3 sides of a cuboid as variables (doubles) # The program should write the surface area and volume of the cuboid like: # # Surface Area: 600 # Volume: 1000 height = 600 width = 600 length = 600 surfaceArea = (height * width + width * length + length * height) volume = (height * width * le...
13049d9569dc1e3a9e3a79cb6ad6a956105b7578
DierSolGuy/Python-Programs
/string.py
103
4.25
4
# Write a program to print a string Vertically n=input('Enter a String:- ') for i in n: print(i)
a188b3bc1e86afe9fa4594b8edd3fe9c235721da
jwraw94/CS50-2019-Projects
/pset6/similarities/helpers.py
2,008
3.765625
4
def lines(a, b): """Return lines in both a and b""" # TODO # Split into lines by endline char \n ["L1", "L2", ... ] alines = a.splitlines() acount = len(alines) i = 0 # Create array to hold the same lines samelines = [] # Find all lines that appear in both a and b, but have not alr...
f8e8265950ef48236919bc2884af12ef53ef5c01
chenkehao1998/geneticAlgorith
/main.py
868
3.65625
4
from route import * from graphics import * cityList = [] # 随机创建25个城市 for i in range(0,25): cityList.append(City(x=int(random.random() * 200), y=int(random.random() * 200))) win = GraphWin("city-map", 800, 800) win.setCoords(0, 0, 200, 200) for city in cityList: circle=Circle(Point(city.x,city.y),1) circle...
c707cd61e1a228ac5f3a2929548d93b9b65c5bc0
yooonar/helloPython
/Container_Loop/3.py
212
3.9375
4
i = [0, 1, 2, 3, 4] for item in i : print(item) for item in range(5) : print(item) for item in [5, 6, 7, 8, 9, 10] : print(item) for item in range(5, 11) : # i == 5 ; i < 11 ; i++ print(item)
fa1a3cd6afed7abee94ce088086531a65fb99d58
Dian82/Assignments
/AdvancedComputerProgramming/ps1/ps1c.py
982
4
4
# Chen Hongzheng 17341015 # chenhzh37@mail2.sysu.edu.cn # Part C: Finding the right amount to save away # Initialization semi_annual_raise = 0.07 return_rate = 0.04 portion_down_payment = 0.25 total_cost = 1000000 downpay_cost = total_cost*portion_down_payment annual_salary = int(input("Enter the starting salary: ")) ...
6424f7f385bc8fb10faceae1e308e970b47f7ecc
tianliuxin/DataStructure
/recursion/binary_search.py
1,241
3.734375
4
""" 二分搜索: 1.用在有序的序列 2.时间复杂度是O(logn) 递归实现 查找失败返回None 取中值 目标大于中值,则从中值右边开始查找 目标小于中值,则从中值左边开始查找 目标定于中值,则返回中值 循环版和递归版比较 递归的实现一般要设置更多的参数,通过函数参数来存储变化的变量,从而通过递归实现 不论是递归还是循环,都要设置好终止条件 """ def binary_search(S,target,low,high): if low > high: return None mid = (low+high) /...
f0859d8748f722b9419e0847e3454589d0c8b4d0
tiagosm1/Python_Nilo_Ney
/exercicios_resolvidos3/exercicios3/capitulo 03/exercicio-03-09.py
931
4.4375
4
############################################################################## # Parte do livro Introdução à Programação com Python # Autor: Nilo Ney Coutinho Menezes # Editora Novatec (c) 2010-2020 # Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8 # Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3 # Terce...
5754ea39f4c4dd570f202a377adac3072e068e45
mumudexiaomuwu/Python24
/02NetworkProgramming/day02/file_server.py
1,346
3.828125
4
""" 文件下载的服务器端 Python中如果函数中没有return的话,默认的是返回return None """ import socket, os def read_file_data(file_name): """获取指定的文件数据""" try: file = open(file_name, "rb") except Exception as e: print("文件不存在.") return None else: # 如果文件过大,会有隐患 file_data = file.read() ...
9d14e51c16f590039369f6e1db1f319bc766d3cb
bansal7/Fundamentals-of-Computer-Networking
/Project_4/utilities.py
672
3.75
4
#!/usr/bin/python import socket import sys def get_my_ip_address(): ''' Returns the IP address of the client in dotted decimal notation ''' s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(("8.8.8.8", 80)) except socket.error , msg: print 'Cannot connect to internet. Error Code : ' + str(msg...
c5d642b45a5287ae96066151b091ec8fa6dc80cd
chudichen/algorithm
/linked_list/swap_pairs.py
915
4.1875
4
# -*- coding: utf-8 -*- """ 反转相邻的两对 解题思路创建三个临时指针,将pointer1和pointer2交换并将pointer3放入递归 https://leetcode.com/explore/learn/card/recursion-i/250/principle-of-recursion/1681/ """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: ...
629f1e40aa3b7b93cf3d6859e7a61661332052ac
dyfloveslife/SolveRealProblemsWithPython
/BasicKnowledge/test_20180619.py
2,151
3.796875
4
# def write_multiple_items(file, separator, *args): # file.write(separator.join(args)) # # # def concat(*args, sep="/"): # return sep.join(args) # # # print(concat("earth", "mars", "venus")) # a = list(range(3, 6)) # print(a) # args = [3, 7] # a = list(range(*args)) # print(a) # def parrot(voltage=1000, sta...
c2e6ff2d00c67e9a4d8e442e7c6bcd119f00aca5
chemplife/Python
/practice_problems/udemy_course_projects/part_3/code_exercise_2/serializer_deserializer.py
5,817
3.53125
4
class Stock: def __init__(self, symbol, date, open_, high, low, close, volume): self.symbol = symbol self.date = date self.open = open_ self.high = high self.low = low self.close = close self.volume = volume class Trade: def __init__(self, symbol, timestamp, order, price, volume, commission): self.s...
1becc5a5d2c04d16e7d7b1800bc9fbc4573e48e1
YuzhongHuang/Bubblepops
/hw5.py
11,077
3.515625
4
# -*- coding: utf-8 -*- """ Created on Sun Oct 19 13:01:36 2014 @author: yuzhong """ """ Anders Johnson Yuzhong Huang Software Design 10/8/14 HW5: Video Game """ import pygame from pygame.locals import * from sys import exit import random import math import time class BubbleModel: """Create a model for our ...
66a30fc0cc3bf27b9575b69bf23bc3b967107fab
tikipatel/Project-Euler
/Problem3.py
1,595
3.96875
4
from math import sqrt from functools import reduce def factors(n): return set(reduce(list.__add__,([i, n/i] for i in range(1, int(sqrt(n)) + 1) if n % i == 0))) ###### http://stackoverflow.com/a/6800214 ###### #This will return all of the factors, very quickly, of a number n. # #Why square root as the upper l...
b35f3125a5712154a5c09d6c55dca9822e6f944b
joseangel-sc/CodeFights
/Arcade/SpringOfIntegration/StringsCrossover.py
1,547
3.75
4
#Define crossover operation over two equal-length strings A and B as follows: #the result of that operation is a string of the same length as the input strings #result[i] is chosen at random between A[i] and B[i] #Given array of strings inputArray and a string result, find for how many pairs of strings from inputArray ...
217de4af905a941011e9aef37fa5f99bd7e782c9
ksoltan/invent_with_python
/formatting.py
502
3.9375
4
import random words = 'eggs ham sausage pomegranite banana olives chicken'.split() def random_word(wordList): x = random.randint(0, len(wordList)-1) return words[x] print('What is your name?') name = raw_input() play_again = False def say_what_you_like(name, rword): print(str('Hello {0}, I know that you...
b3abb7fb36c5f332db4d02cea2a572a13d673131
jvtanner/swizzler
/swizzler.py
2,965
4
4
#!/usr/bin/env python3 """ Stanford CS106A Swizzler project """ import sys def first_part(s): """ Isolate the beginning symbolic characters in the string, if they exist. Return them as a string. >>> first_part('++jingle') '++' >>> first_part('k') '' >>> first_part('') '' >>> ...
feb528580a5bc16176e6a9cc9161fcf3b3a6a9be
sarfarazsyed/Coursera
/Data Structures and Algorithms Specialization/algorithmic-toolbox/week2_algorithmic_warmup/1_fibonacci_number/fibonacci.py
193
3.578125
4
# Uses python3 def calc_fib_opt(n): a = 1 b = 1 if n <= 1: return n for i in range(2, n): a, b = b, a + b return b n = int(input()) print(calc_fib_opt(n))
fd9b6ee0d68ab70d458edd359d7d9e5c760fafdd
jamesgray007/northwestern-predictive
/CIS435-Machine_Learning/Assignment 1/435_assignment_1_jump_start/435_assignment_1_jump_start/435_assignment_1_jump_start_v001.py
3,762
4
4
# Assignment 1: Python Jump-Start Program # # We show how to work with a variety of data structures in Python, # and in the process begin an analysis of the Wisconsin Dells case study data. # For purposes of demonstration, we will focus on the Wisconsin Dells visitors # who go bungeejumping. # here are a few...
7b06e2402f71f016aef61f2896f3e0dc0485b210
NorthcoteHS/10MCOD-Dimitrios-SYRBOPOULOS
/modules/u3_organisationAndReources/naming/commentMe.py
417
3.640625
4
""" Prog: commentMe.py Name: Dimitrios Syrbopoulos Date: 18/04/18 Desc: a calculator that determis the perimeter of a circle """ #print welcome message print('Welcome to the Circle Calculator!') #make user input radius r = input('Enter a radius: ') r = int(r) #calculate area and print it area = 3.14 * r * r print('The ...
2eb59fae03b9c3d8b935e79b57b4a7c87e1d7b29
Bandaru-Swathi/Day1_programs
/addition.py
70
3.609375
4
a=input("enter a="); b=input("enter b="); sum=a+b; print "sum=",sum
3dd69cbc05499b5d42df0e75b7685f79511a2976
sajan777/ML_Begins
/DUCAT/magicnumber.py
314
3.640625
4
n = int(input('Enter the number: ')) temp = n sum = 0 rev = 0 while(temp>0): temp1 = temp%10 temp = temp//10 sum = sum + temp1 digit = sum while(digit>0): save = digit%10 rev = rev*10+save digit = digit//10 mul = sum*rev if(mul==n): print("Hell yeah magic") else: print("No magic")
98f4ac58213e3d1db205ba34d9789a2957d08f17
laconicwolf/cryptopals-challenges
/set_1_challenge_5.py
658
3.59375
4
def repeating_key_xor(message_bytes, key): """Returns message XOR'd with a key. If the message, is longer than the key, the key will repeat. """ output_bytes = b'' index = 0 for byte in message_bytes: output_bytes += bytes([byte ^ key[index]]) if (index + 1) == len(key): ...
842b6f90d1c30dd62a37a0799729ee776d385f3b
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/kvrsha004/question4.py
1,656
3.921875
4
""" Question 4 / Assignment 8: 0Palindromic prime finder Shaheel Kooverjee - KVRSHA004 8 May 2014 """ import sys sys.setrecursionlimit (30000) def palindrome(string): #using palindrome function from question1.py if string == "": #base case where string is empty return True else: if ...
6d7857e170320489ce55ce42758bc53afa01fee8
venkatarajasekhar/tortuga
/packages/vision/python/arclength.py
2,116
3.953125
4
# Copyright (C) 2010 Maryland Robotics Club # Copyright (C) 2010 Jonathan Sternberg <jsternbe@umd.edu> # All rights reserved. # # Author: Jonathan Sternberg <jsternbe@umd.edu> # File: packages/vision/python/buoy.py # # Requirements: # - Must have opencv python bindings # - Package list: # - python-openc...
ee5e6f439d5ce982c8f1b88dbd9eba639b9f2746
viing937/codeforces
/src/63A.py
237
3.625
4
# coding: utf-8 n = int(input()) d = {'rat':0, 'woman':1, 'child':1, 'man':2, 'captain':3} people = [] for i in range(n): tmp = input().split() people.append([d[tmp[1]], i, tmp[0]]) people.sort() for i in people: print(i[2])
7675847168e7549654278d86fe2a519ef54e8731
melardev/PythonBasicsSnippets
/loops/for_in_iterable.py
200
4.03125
4
fruits = ['Apple', 'Banana', 'Kiwi', 'Mango'] for fruit in fruits: print(fruit, end=' ') print() # print new line for fruit in fruits[::-1]: print(fruit, end=' ') print() # print new line
b1e968055a83f7454d6f7c7a30aba77a78b13ac6
vitaliytsoy/problem_solving
/python/medium/partition_list.py
1,681
3.84375
4
""" Given the head of 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. Example 1: Input: head = [1,4,3,2,5,2], x = 3 Output: [1,2,2,4,3,5] Example 2: Inp...
277266fffe70eded36e72837f0f8f34790059958
amolsmarathe/python_programs_and_solutions
/2-Basic_NextConceptsAndNumpy/6-FibonacciUsingFunction.py
1,393
4.21875
4
# QUE: A program should ask for user input about how many numbers of the Fibonacci series does he want to print? # Then asks do you want to set a upper limit for the maximum number where you should stop? # Accordingly print the fibonacci series. n = int(input('How many numbers do you want to print from the Fibonacci s...
e551910fb9c494ee55cea8af5138648b66afbae1
imMaxidev/Python-MinTIC2021
/Modulo 1 - Python/Class7.py
2,859
4.21875
4
#Algoritmo 1. Detectar que el numero es 5 """ number=float(input("Digite el numero 5: ")) if number==5: print("El número es 5") else: print("El número no es 5") #Algoritmo 2. Detectar que el numero es divisible entre 5 number=float(input("Digite un número divisible entre 5: ")) if number%5==0: print("El...
239ef0a5588d0d27765f21c2da0138d8d9dc7a8c
charlesreid1/probability-puzzles
/scripts/dicey_question.py
764
4.09375
4
# Dicey Question # You are about to roll five regular dice. You win if you roll exactly # one six. You lose if you roll no sixes. Are you more likely to win # than lose, or are you less likely to win than lose? import random def dicey_question(): samples = 10000 wins = 0 losses = 0 for i in range(sam...
f888d0d503a1c46df5c522dbc4d61c81fa4dbac3
ppcrong/TestPython
/TestPython/async_queue_test.py
1,466
3.5625
4
import asyncio # https://www.maxlist.xyz/2020/04/03/async-io-design-patterns-python/ # 消費者 async def consumer(n, q): print('consumer {}: 進入商店'.format(n)) while True: item = await q.get() print('consumer {}: 購買產品 {}'.format(n, item)) await asyncio.sleep(0.15) q.task_done() ...
fe0b50f7f5fb7ad3101d0679ad023e879723bbad
JeffersonLobato/Curso-Completo-de-Python-no-Youtube
/Curso_Python/modulo.py
1,363
3.84375
4
def lista_funcao(lista): for cor in lista: print(cor) def nome_completo(primeiro_nome="", ultimo_nome="", nome_do_meio=""): primeiro_nome = primeiro_nome ultimo_nome = ultimo_nome nome_do_meio = nome_do_meio if nome_do_meio != "": nome_completo = "O nome digitado foi " + primeiro_n...
e18396c3d4872f08db50bd75c9c9074a37dbd09b
Kashinggo/SZU_gwt_official_account_spider
/sorter.py
1,916
3.546875
4
def showList(lines): number = 0 print('======================================================') for line in list(lines): if line[0] == '1': number += 1 information = line.split('$') title = information[1] department = information[2] print(n...
bc71584ab87a1084c894d2b414a5009a2eee1776
xjh1230/py_algorithm
/test/find_duplicates.py
1,566
3.6875
4
# -*- coding: utf-8 -*- # @Time : 2019/8/14 11:34 # @Author : Xingjh # @Email : xjh_0125@sina.com # @File : find_duplicates.py # @Software: PyCharm class Solution: def __init__(self): ''' 给定一个整数数组 a,其中1 ≤ a[i] ≤ n (n为数组长度), 其中有些元素出现两次而其他元素出现一次。 找到所有出现两次的元素。 你可以不用到任何额外空间并在O(...
d5a03a886d3216a44ec5c8ba3f63d2c77ea29c3e
jnthmota/ParadigmasProg
/Exercicio5/Exemplo5.py
1,095
3.71875
4
class Contato: def __init__(self, nome, numero): self.nome = nome self.numero = numero def cadastro_da_contatos(): menu = "1 - Cadastrar\n2 - Listar\n0 - Sair\n" op = input(input(menu)) while op != 0: if op == 1: try: f = open(...
ddf54d65f063855a96907b708df5f55c826463b8
joaolucas-prog/Aprendendo-python
/4.OO2/Aula 1 ( Heranças ).py
1,308
4.0625
4
# para definir uma herança no python vc cria uma classe normal e depois quando for criar uma classe filha # vc usa o class classe_filho(classe_mae): # e chamar o metodo super(atributos da classe mae) #em pythom por enquanto não sei uma forma de deixar os metodos da classe mae privada pq da erro #então coloca apenas 1 _...
a9fe02293883871fbe74e497244787de080ab1fa
jagruthnath/MSIT_CT
/CT/L1P7.py
133
4.21875
4
n=int(input("Enter n : ")) def fact(n): if n==1 or n==0: return 1 else: return n*fact(n-1) print("Factorial is ",fact(n))
a160436c58771b1764f99e93e26a1025f6d21622
sandeepkumar8713/pythonapps
/21_firstFolder/05_find_dist_in_matrix.py
4,239
3.59375
4
# https://www.geeksforgeeks.org/distance-nearest-cell-1-binary-matrix/ # https://leetcode.com/problems/01-matrix/ # Question : Given a matrix (m*n) filled with X and 0(zero). Calculate the distance from # nearest 0 for all cells marked with X. The distance of four neighboring cells # (top,bottom,right,left) will be 1. ...
52513bf3f50726587bee800f118e2ac0fa00d98b
hongta/practice-python
/sorting/quick_sort.py
1,037
3.875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def quick_sort(a): _quick_sort(a, 0, len(a)-1) return a def _quick_sort(a, lo, hi): if lo < hi: j = partition2(a, lo, hi) _quick_sort(a, lo, j-1) _quick_sort(a, j+1, hi) def partition(a, lo, hi): # simply select first element as...
d135d9c203c0f7da44407fadac5b4de0af9b6bb1
fagan2888/pythonStudy
/src/io/file_io.py
1,928
3.6875
4
# I/O操作 # 一次性读取文件 def read(path): with open(path, 'r') as f: print(f.read()) # readline()循环读取文件 def loop_read(path): f = None try: f = open(path, 'r') # 打开文件 for line in f.readlines(): # 循环读取每行文本 print(line.strip()) # 打印删除过末尾的'\n'的文本 except Exception as e: ...
2d0470eb3e2107ec6852adeb872fedd410ced358
grayondream/algorithm-forth
/src/sort/selection_sort.py
1,610
3.734375
4
def selection_sort(l, start, end, hook_func=None): ''' @brief 选择排序算法[start, end] @param l 需要进行排序的list @param start 开始位置 @param end 结束位置 @param hook_func 进行可视化的函数 ''' count = 0 for i in range(start, end + 1): minindex = i for j in range(i + 1, end + 1): ...
65f3b034b15a42c24b73358f5606c8acfb9a78a9
tackle-hard/Python_Development
/Programs/SquareRoot.py
470
3.875
4
import fileinput def sumArray(): array1=[1,2,3,4] for number in array1: print(number) def sumInputDec(): array=input('Input series of decimal numbers separated by comma : ').split(',') sum=0 for number in array: sum+=float(number) print('the sum of the numbers is ', sum) #Testing the range and how the v...
99b0ae191d808eb2ccdc07dac6a18d4cbd7eb6ca
tigiridon/python
/algorithms_and_data_structures/HW2/task_3.py
484
4.03125
4
# Задание №3 # Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. # Например, если введено число 3486, то надо вывести число 6843. n = input('Введите число: ') i = -1 rev = '' while i >= -1 * len(n): rev = rev + n[i] i = i - 1 print(f'Число в обратном порядке: {rev}'...
4e0bc68e333664c8a7a399340beaceb3cd7e0ef0
Ibraheemshwiki/python_Fundamentals
/_python/flask/flask_fundementals/hello_flask/Understanding Routing/server.py.py
804
3.90625
4
from flask import Flask # Import Flask to allow us to create our app app = Flask(__name__) # Create a new instance of the Flask class called "app" @app.route('/') # The "@" decorator associates this route with the function immediately following def hello_world(): return 'Hello World!' @app.route(...
772252dba0ef71582dc30fa701833cebf2431461
isaanca/shape-art
/inheriting_shapes.py
3,163
3.90625
4
import Tkinter # built-in Python graphics library import random game_objects = [] class Shape: def __init__(self, x, y): '''Create a new circle at the given x,y point with a random speed, color, and size.''' self.x = x self.y = y self.x_speed = random.randint(-5,5) ...