blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
1cf43c3c2e4ca2e790259cfd6d74a0976059281b
simonvidal/Python
/tuplas.py
1,004
4.03125
4
# -*- coding: utf-8 -*- # Autor: Enmanuel Cubillan # Tuplas en Python mi_tupla = (1,'Enmanuel') print 'Mostrando un elemento de la tupla:',mi_tupla[1] print 'Tupla:',mi_tupla # convierte una lista en tupla # método list mi_lista = list(mi_tupla) print 'Tupla convertida en Lista:',mi_lista # convierte una tupla en...
7058760172fc808ce28cac36e8d8b2aee2378940
caesarjuming/PythonLearn
/com/test1.py
4,806
3.890625
4
__author__ = 'Administrator' # python处理的每一样东西都是对象,像模块,函数,类都是对象。 # Python是强类型的,也就是只能对相应类型做相应的操作,例如只能对字符串进行字符串操作,但他是动态类型 # python数字类型有整数,浮点类型,复数,十进制数,有理分数,集合等 print(1+1) print(2.11+3) print(2*4) print(2**3) import math print(math.pi) print(math.sqrt(4)) import random print(random.random()) print(random.choice([1,2,3,4...
5a4bbadfcdb599c207f1ade512b03d85118f2e74
Alexan101/students
/main.py
5,868
3.71875
4
class Student: def __init__(self, name, surname, gender): self.name = name self.surname = surname self.gender = gender self.finished_courses = [] self.courses_in_progress = [] self.grades = {} def rate_lecturer(self, lecturer, course, rate): if (isinstanc...
3b2fcea13b2469228b39e964a76e00e42b3c28d4
gurs56/pythonprograming
/test.py
792
3.96875
4
""" #globe scope num = 10 def change_num(num): #function scope num += 5 print("inside function num is {}".format(num)) #intergers are passed by value, i.e we pass a copy to functions change_num(num) print("out{}".format(num)) nums = [1,2,3,4,5] def change_nums(vals): for index in ran...
4a5e75314ea40f2fb1f302a031baad563468f5f3
tusharsappal/Scripter
/python_scripts/python_cook_book_receipes/date_and_time/calculating_time_periods_in_date_range.py
532
4.03125
4
__author__ = 'tusharsappal' ## Credits Python Cook Book Solution 3.3 ## This program finds the time period in weeks between the given date range from dateutil import rrule import datetime def weeks_between(start_date, end_date): weeks=rrule.rrule(rrule.WEEKLY,dtstart=start_date,until=end_date) print "The num...
6d31057c5a5a061f0172087ed962a0edda26f50b
rjayswal-pythonista/DSA_Python
/Practice/test2.py
422
3.5
4
class Solution: def suggestedProducts(self, products, searchWord): list_ = [] products.sort() for i, v in enumerate(searchWord): products = [p for p in products if len(p) > i and p[i] == v] list_.append(products[:3]) return list_ sol = Solution() products = ...
759b84a535c620d24513da826ba8026f90795ad2
guyunzh/extract_data
/extract_data.py
853
3.640625
4
prices={ "ACME":45.32, "AAPL":612.76, "IBM":205.44, "HPQ":37.21, "FB":10.75 } '''利用字典推导式来从字典中取出需要的数据''' #Make a dictionary of all prices over 200 p1={key:value for key,value in prices.items() if value >200} #print {'AAPL': 612.76, 'IBM': 205.44} #Make a dictionary of tech stocks tech_names={'AAPL','IBM','HPQ','MSFT'...
184c0f625459a5377e41ee735f7efef04b803c0a
Yurun-LI/CodeEx
/.history/TwoSum_20210719232906.py
370
3.703125
4
from typing import List class Solution: def twoSum(self,nums:List[int],target:int)->List[int]: dic = {} Len = len(nums) for i in range(Len): if nums[i] in dic: return [i,dic[nums[i]]] dic[target - nums[i]] = i return None nums = [1,2,3,6,7] ...
baff4b4109f9c21948ba543f372fda507def8c30
dylanhoover/SCU-Coursework
/COEN140/lab1/class3.py
310
3.6875
4
class Person: def __init__(self, name, jobs, age=None): self.name = name self.jobs = jobs self.age = age def info(self): return(self.name, self.jobs) rec1 = Person('Bob', ['dev','mgr'],40.5) rec2 = Person('Sue', ['dev','cto']) print(rec1.jobs) print(rec2.info())
076be9d4edd312dea2afa44759a1e3299340b6a2
kedarpujara/BioinformaticsAlgorithms
/Rosalind1/Prob56/cycleToChromosome.py
1,238
3.65625
4
def cycleToChromosome(Nodes): list1 = [] listR = [] for i in range(len(Nodes)/2): if Nodes[2*i] < Nodes[2*i+1]: val = i+1 else: val = -(i+1) list1.append(val) for i in list1: if i >0: listR.append("+"+str(i)) if i<0: listR.append(str(i)) print "(" + " ".join(listR) + ")" return list1 def r...
6a7e700e589519ce61c04e3f8de184fcc458b319
christensonb/Seaborn
/seaborn/sorters/sorters_3.py
2,487
3.609375
4
""" This just contains some standard functions to do sorting by """ import sys from random import random, seed __author__ = 'Ben Christenson' __date__ = "8/25/15" class by_key(object): def __init__(self, keys, comp=None): self.keys = isinstance(keys, list) and keys or [keys] self.comp = comp or (...
19807581a63d8d60393619626413609987acfabf
fffDroot/111.py
/prog1.py
259
3.84375
4
import sqlite3 con = sqlite3.connect(input()) cur = con.cursor() res = cur.execute("""SELECT DISTINCT title FROM genres WHERE id IN (SELECT genre FROM films WHERE year > 2009 AND year < 2012)""").fetchall() for elem in res: print(elem[0]) con.close()
63ec2461978aa10ca1f03d14192086a035f73035
tarikbulbul/GorselProgramlamaVize
/soru2.py
153
3.96875
4
url =input("Url giriniz : ").split(".") if url[0] == "www" and url[2] == "com" : print("Url Doğru") else : print('Girilen url hatalıdır.')
75a74f2d0610371edd91c80817310340009e75cc
amarelopiupiu/python-exercicios
/ex26.py
427
3.90625
4
# Escreva um programa que pergunte a quantidade de dias pelos quais ele foi alugado e a quantidade de Km percorridos por um carro alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$0,15 por Km rodado. dias = float(input('Quantos dias o carro foi alugado? ')) km = float(input('Quantos km foram...
9339060107bef177c65e11f8f90005a64e3ff59f
L200170153/coding
/da best/uas/uas3.py
203
3.578125
4
def putar(l): k = [] a = l[-2:] b = l[0:len(l)-2] for i in a: k.append(i) for l in b: k.append(l) print(k) l = [x for x in input().split(',')] putar(l)
bfb002d7e3ba1eb86e392416d66b964cdb4b9e1f
dedin/sides
/sorts/sorts.py
4,742
4.375
4
# BUBBLE SORT # Go through the list over and over again, swapping as you go(if necessary) # until you go through the list w/out swapping. Can reduce number of iterations # cos on every walk of the list, the largest ends up bn at its right position # Simple, efficient on small data, but bad on large data # Not good for ...
2873a5a374c9a867ee52026da7361d893e258ccd
vibhorsingh11/hackerrank-python
/04_Sets/11_TheCaptainsRoom.py
1,012
4.1875
4
# Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an infinite amount of rooms. # # One fine day, a finite number of tourists come to stay at the hotel. # The tourists consist of: # → A Captain. # → An unknown group of families consisting of K members per group where K ≠ 1. # # The Captain was giv...
8bab9d1b985995535ccab28c4b306717abac0f1d
victormruiz/ASIR
/LM2/python/entrega1/ejercicio6.py
691
3.765625
4
from random import randint print("JUEGO DE MULTIPLICACIONES") vueltas = int(input("¿Cuantas multiplicaciones quieres hacer? ")) correctas=0 for i in range(vueltas): num1 = randint(2, 10) num2 = randint(2, 10) resultado=num1*num2 respuesta=int(input("¿Cuanto es %d x %d?: " % (num1,num2))) if respuest...
7d6f55e12d0a2b95ecdde65ee7fb0e38376210f5
P01Alecu/LFA_Simulare-AFD
/simulare_afd.py
2,735
3.71875
4
###########Simulare AFD ##in fisierul 'in.txt' se gasesc datele de intrare ##fisierul este de forma: ##stare_initiala Stari_finale ##cuvant cuvant cuvant...... ##litera starea_din_care_pleaca starea_in_care_ajunge ##... ##litera starea_din_care_pleaca starea_in_care_ajunge def parcurgere(start, sir): o...
cc06a3e82dfb5ad0e06ee4a5177473727da338ad
pandarison/training2
/w1_family/template.py3
355
3.734375
4
{USERCODE} _,x,y = input().split(" ") x = int(x) y = int(y) solution = Solution() for i in range(x): a, b = input().split(" ") a = int(a) b = int(b) solution.setFamily(a, b) for i in range(y): a, b = input().split(" ") a = int(a) b = int(b) if solution.isFamily(a, b): print("Ye...
f9e7f1ac8dc5d3633a6b96a918164faf08628500
asiffmahmudd/Python-Specialization-on-Coursera
/Programming for Everybody (Getting Started with Python)/Week 5/Assignment 1.py
158
4.0625
4
hrs = float(input("Enter Hours:")) rate = float(input("Enter rate:")) if hrs <= 40 : print(hrs*rate) else: x = rate*40+rate*1.5*(hrs-40) print(x)
cf8de94dc427c04f3daeca65dde2f3057713e0f6
xwind-h/coding-practice
/leetcode/ConvertSortedArrayToBinarySearchTree.py
1,445
3.765625
4
# Definition for a binary tree node. from collections import deque class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def sortedArrayToBST(self, nums): def toBST(l, u): if l > u: return None...
8536f59d3ae9b45f9e550f5e14823bf614f224e8
killedman/DoTheQuestion
/20200214_02.py
1,208
3.90625
4
#! /usr/bin/env python """ 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。 说明: 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? 示例 1: 输入: [2,2,1] 输出: 1 示例 2: 输入: [4,1,2,1,2] 输出: 4 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/single-number 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List class Solutio...
0e6fde19a2a3519f88f94cd71d182569654dd697
manshan/pyworkspace
/test1.py
177
4.0625
4
def fibonacci(i): if i < 1: return 1 if i == 1 or i == 2: return i return fibonacci(i-1) + fibonacci(i-2) if __name__ == '__main__': print fibonacci(10)
ab4604be0d7e732cfb94fd7045b5edb1f250eeb9
VinogradovAU/myproject
/python_less/lesson-3/less-3-4.py
941
4.125
4
# -*-coding:utf8;-*- """ Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции возведения числа в степень. "...
e9542054423160f9126417e6aee4baa5f2f1f2e9
crazy-learner-xyz/lc
/0547. Number of Provinces/solution.py
970
3.546875
4
import collections class Solution(object): def findCircleNum(self, isConnected): """ :type isConnected: List[List[int]] :rtype: int """ # Reshape the data structure diction = collections.defaultdict(list) for i in range(len(isConnected)): for ...
c984c502d22f8a4bb96ec6a19cf4df3bb59619b5
yaseen-ops/python-practice2
/21readFile.py
535
3.8125
4
employee_data = open("employee_file.txt", "r") # r=read; w=write; a=append; r+=read/write # print(employee_data.readable()) # Check the file is readable or not # print(employee_data.read()) #Read the whole file # print("-------------------") # print(employee_data.readline()) # Read by lines, prints the first line and...
5001bafc9dd553b52500d1365dc79b33b8cb194b
yandre-dle/Catatan_PRGT_PYTHON
/PYTHON-1/5- Aplikasi Belanja/17. Control Flow/x1.py
343
3.65625
4
apple_price = 2 # Berikan 10 ke variable money input_count = input('Mau berapa apel?: ') count = int(input_count) total_price = apple_price * count print('Anda akan membeli ' + str(count) + ' apel') print('Harga total adalah ' + str(total_price) + ' dolar') # Tambahkan control flow berdasarkan perbandingan antara ...
6f266d2cccfb5d67c12e58af9b6b1a574ee58ffa
knight-byte/Codeforces-Problemset-Solution
/Python/A_Even_Subset_Sum_Problem.py
558
3.578125
4
''' Author : knight_byte File : A_Even_Subset_Sum_Problem.py Created on : 2021-04-21 11:16:19 ''' def main(): n = int(input()) arr = list(map(int, input().split())) odd = [] for i in range(n): if arr[i] % 2 == 0: print(f"1\n{i+1}") break else: ...
7bc6776a8298b2b0392cab478d94d9a7fa88e75b
CristianoFernandes/LearningPython
/exercises/Ex_013.py
356
3.859375
4
print('########## Exercícios de Python ##########') print('########## Exercício 013 ##########') salario = float(input('Digite o salário do funcionário: R$')) reajuste = float(input('Digite o percentual para reajuste: ')) print('O salário do funcionário reajustado em {}% será de R${}'.format(reajuste, salario + ...
f052e9746d0ec980e824a0450d49ca32907b7ced
lupomancer/Python
/Midterm/course_selector.py
4,518
4.15625
4
#! /usr/bin/env python3 """ This module builds a program workload for a general interest computing program. Courses are selected from a course calendar. Being a general interest continuing studies program and there are no program requirements either in number of, ordering, or specific required courses. Once a user h...
4b45806fcbbcde8c45565f0c6d49aecd37241328
LuisAraujo/Simple-Unit-Testing
/www/code_examples/code2.py
90
3.671875
4
max = 0 for i in range(10): valor =input() if(valor > max): max = valor print(max)
f1d3bfe43edd5b471ec066a4a4ff77d862949986
lighttransport/nanosnap
/tests/gen/common_util.py
1,160
3.625
4
import numpy # NOTE(LTE): We cannot use numpy.iscomplex() whether input value is complex-value, # since it will return False for complex-value whose imaginary part is zero. # # arr : numpy 1D or 2D array def print_c_array(arr): c_arr = [] if numpy.isfortran(arr): arr = numpy.transpose(arr) if len...
5a9f033a0b63bd6149e84d70f24b706a7f073105
estradanorlie09/hello-python
/hello.py
646
3.890625
4
print("Hello, World!") print("My name is {}. I am {} y/o."\ .format("Norlie",16)) print("Adnu", 2018, sep="-", end="") print("CSNHS") print("My spirit animal is".format(data["animal"])) print("my reason{}".format(data["reason"])) print("my hobby{}".format(data["hobby"])) print("my profession{}".format(data["pro...
6da7023392314e57c75508daec871a5643857d13
ledbagholberton/holbertonschool-machine_learning
/supervised_learning/0x10-nlp_metrics/1-ngram_bleu.py
2,484
3.828125
4
#!/usr/bin/env python3 """ references is a list of reference translations each reference translation is a list of the words in the translation sentence is a list containing the model proposed sentence n is the size of the n-gram to use for evaluation Returns: the n-gram BLEU score """ import numpy as np de...
50e7818b9cf109b389cad6920dc123329535c411
barakbanin/varonis
/test1.py
302
3.515625
4
class MagicList: def __init__(self): self.lst = list() self.counter=0 def __setitem__(self, i, item): if len(self.lst)==0: self.lst.append(item) self.counter+=1 def __getitem__(self, i): return self.lst[i]
52a1eb439c48f96fbee45170ca77e6d31c84a906
ayushgarg95/python_scripts
/input_space_separated.py
243
4.3125
4
#!/usr/bin/env python x=raw_input('Enter a list of numbers separated by space: ') # nums is an array which has each element of input nums=x.split() for i in nums: if not i.isdigit(): print ' Not a number :',i else: print 'Numer :',i
a5f4d37c09fcbc4d531d666bec92b4623854ffae
br71/py_examples
/nth_fibonacci.py
765
3.765625
4
# Recursive solution # O(n^2) time | O(n) space def get_nth_fib1(n): if n == 2: return 1 elif n == 1: return 0 else: return get_nth_fib1(n - 1) + get_nth_fib1(n - 2) # Recursive solution with dictionary # O(n) time | O(n) space_ def get_nth_fib2(n, mem={1: 0, 2: 1}): if n in ...
a8926f72e29d6058f357533d1746b5faa91aae6c
souradeepta/PythonPractice
/code/12-16/binary-search-recurrsive.py
1,271
3.875
4
from typing import List, Any def binary_search_recurrsive(input: List, target: Any) -> None: """Binary search with Time O(Log(n)) and Space O(Log(n))""" if not input: return None left = 0 right = len(input) return helper(input, target, left, right) def helper(input: List, target: Any, le...
e3c077a91dc270641f7b8b82ec36e6e42e222e0c
aloyalways/Competitive-Programming-DSA-in-Python-
/Tree/Height of BT.py
495
3.796875
4
class Node: def __init__(self,key): self.left=None self.right=None self.val=key def height(self,root): if root is None: return 0 lheight=root.height(root.left) rheight=root.height(root.right) if lheight>rheight: return lheight+...
89ac6fdabbe5bebd9f41e511ca325af79a5bad29
mjoze/kurs_python
/kurs/03_kolekcje/tuple_set.py
180
3.515625
4
"""Utwórz dowolną krotkę, w której elementy mogą się powtarzać. Przekształć ją w set.""" a = ("a", "w", "reksio", "e", "e", 1, 1, "reksio") print(a) b = set(a) print(b)
a7c08e1e9db6afc9377a9cd823a6111774c74e87
MrNierda/SpeechRecognition
/audio_to_text.py
1,532
3.515625
4
import speech_recognition as sr # from operation_produced import main import operation_produced import language def recognize_audio(spoken_language=language.Language.FR): """ Activate microphone to listen to the user Return the audio as a string """ r = sr.Recognizer() with sr.Microphone() as s...
07a52959e6445acb083827b64f0326356341ea73
la-ursic/redtape
/lists.py
2,921
4.21875
4
''' list1 = [1,2,3,4,5,2,32,53,4,333,57,90] list2 = ["A","B"] list3 = ["A",1,2,3,4,5,6,7,8,9] list4 = [list1,list2,list3] #print(list4) list1.append(6) print(list1) list1.extend([7,8]) print(list1) list1.insert(2,"melon") print(list1) list1.pop(3) print("POP") print(list1) list3.reverse() print("REVERSE") print(list3)...
c33b82fa7c19dabcfdfd10b761583ffd860812e9
JF-Ar/processos-seletivo
/exercicios de treino/aula14/exe60.py
499
3.984375
4
'''from math import factorial n = int(input('Digite um numero para calcularmos o seu fatorial: ')) fat = factorial(n) print('{}! é igual a {}'.format(n, fat))''' '''from math import factorial''' n = int(input( 'Digite um numero para calcularmos o seu fatorial: ')) c = n fatorial = 1 print('Calculando {}! ...
ab345d2b899c8a84a4b6dfd02cca6b02f76208c3
BarisAkkus/Main
/Sezon1/Ders12-Blocks.py
549
4.03125
4
name = input("Please enter your name: ") age = int(input("How old are you, {0}".format(name))) print(age) #if age >=18: # print("You can vote") # print("Please put an X in the b0x") #else: # print("Please come back in {0} years".format(18-age)) #elif age ==900: # print("Sorry , Yoda, you die in Return of t...
3d02f3a418d344cec6357d8488dd876d90c0fc51
ArnoutAllaert/Informatica5
/Toets/Verkeersdrukte.py
578
3.515625
4
#input dv = float(input('verkeersdichtheid van het vrachtvervoer op het eerste rijvak: ')) vv = float(input('snelheid van het vrachtverkeer op het eerste rijvak: ')) da = float(input('verkeersdichtheid van het personenvervoer op het tweede rijvak: ')) va = float(input('snelheid van de personenwagens op het tweede rijva...
e72ffc302b0b54369ae0349655ee4e980f2d76dc
mukasama/portfolio
/Python Codes/lab 2.py
901
3.984375
4
import turtle import time n = int(input("Enter the number of sides for the polygon: ")) print(n) turtle.down() r=int(input("Enter amount of red: ")) if r<0 or r>1: print("Number not between or equal to 0 and 1. Run Program again.") g=int(input("Enter amount of green: ")) if g<0 or g>1: print...
ff6fea0c935540d60596820b3f7883356b9c7ac5
LuisTavaresJr/cursoemvideo
/ex23.py
229
3.703125
4
n = int(input('Digite um número entre 0 e 9999: ')) u = n // 1 % 10 d = n // 10 % 10 c = n // 100 % 10 m = n // 1000 % 10 print(f'A unidade é {u}') print(f'A dezena é {d}') print(f'A centena é {c}') print(f'A milhar é {m}')
d38c414fac8ab751d1748d31142c55121a1784bb
LiuJunb/PythonStudy
/book/section-5-条件/01-if语句.py
557
4.15625
4
# 1.if 语句的使用 cars = ['bm', 'ca', 'bc', 'jl'] for value in cars: if value == 'bm': print('宝马') elif value == 'ca': print('长安') else: print('其它') if True: print('True') # 2.比较字符窜是否相等 print('bm' == cars[0]) # True print('ca' == cars[1]) # True print('CA' == cars[1]) # False ...
85c728489cfac207918b6e979a93f3443d8f92a9
JeanneBM/Python
/Owoce Programowania/R13/15. Hello_world.py
606
3.84375
4
# Ten program wyświetla etykietę wraz z tekstem. import tkinter class MyGUI: def __init__(self): # Utworzenie widżetu okna głównego. self.main_window = tkinter.Tk() # Utworzenie widżetu Label zawierającego # komunikat 'Witaj, świecie!' self.label = tkinter.Label(self.main_...
0eae6b87fd426ee83c716ff93a1e570b29d8f01f
BayoOlawumi/DS
/functions/class_et_object3.py
756
3.78125
4
class Food: def __init__(self, name,klass, color, taste, quality): self.name =name self.klass = klass self.color = color self.taste = taste self.supplement = False self.quality =quality self.supplement_food() def change_taste(self, new_taste): sel...
0d74d05756e14982f5d2c2d2dc591da67abb0966
AHartNtkn/Hash-Tables
/applications/word_count/word_count.py
499
4.03125
4
from collections import Counter import re def word_count(s): c = Counter() for w in re.split("\s", s): if w not in '":;,.-+=/\\|[]{}()*^&': c[w.lower().strip('":;,.-+=/\\|[]{}()*^&')] += 1 return dict(c) if __name__ == "__main__": print(word_count("")) print(word_count("Hell...
b07afb9dfee5f0a117d142526586d2b746c0687a
adeshosho/python-THW-
/ex6.py
558
3.96875
4
types_of_people = 10 x = f"There are {types_of_people} types of people" binary = "binary" do_not = "don't" y = f"Those who know {binary} and those who {do_not}" print(x) print(y) print(f"I said: {x}") # imprimimos lo que esta en X print(f"I also said: '{y}'")#imprimimos lo que esta en y hilarious = False #valor b...
cce5ce57ba5f714f8cc8ba9b72be21234bbd8fb2
DanielGaszczyk/AdventOfCode2020
/Day2/Day2.py
990
4.0625
4
#Opening and reading file def readFile(fileName): inputFile = open(fileName, 'r') inputNumbers = inputFile.read().splitlines() inputFile.close() return inputNumbers def findAns(): numbersArray = readFile("inputDay2.txt") #replace with your file with data result = 0 for y in range(len(num...
e7de2e2de1c81d20c6801bf96b3e774bf63cd727
Dropssie/learningpython
/helloworld.py
113
3.859375
4
print('Hello, World!') for i in range(10): print(i) # Example while while i < 50: print(i) i += 1
4ceabfdaf9a481139ea60d06c5182cdbf64dde41
frombeck/Programming-Using-Python
/prime_numbers.py
267
4.125
4
max=int(input("Find primes upto what numbers?")) primeList=[] for x in range(2,max+1): isPrime=True for y in range(2,int(x**0.5)+1) : if x%y==0: isPrime=False break if isPrime: primeList.append(x) print(primeList)
a288b5089d5e48673abe537d104fd524a21eb865
acp21/WMU-Accessability
/acess.py
768
3.96875
4
# This is a very simple program that simply removes a certain line of characters from a text file # It was written for accesability reasons as certain character strings can cause problems with screen readers # Written by Adam Pohl import sys # Get name of file to edit fileName = sys.argv[1] # Get fileName without fil...
7b2f37b83036df7d2fee1e8258309b66cdaaff6b
meighanv/05-Python-Programming
/lab-set-lecture.py
1,577
4.375
4
#Set contains a collection of unique values #and works like a mathematical set #All the elements in a set must be unique, no two elements can have the same value #Sets are unordered #Elements stored in a set can be of different data types mySet= set(['a','b','c']) print(mySet) mySet2 = set('abc') print(mySet2) myS...
ee92376a0d42ab400cc1af7094c662a2f7c35824
damiano1996/DataIntelligenceApplications
/project/dia_pckg/Utils.py
842
3.546875
4
""" Here we have general functions that are used in different classes. """ import os import numpy as np def check_if_dir_exists(path, create=False): """ :param path: directory path :param create: create dir if does not exist? :return: """ if not os.path.isdir(path): if create: ...
ceddc5cbac679bdaa65976a9e89c14a999143d5c
yemgunter/inscrutable
/write_rand_numbers.py
313
3.84375
4
#### This program writes 100 random numbers to a file ## ## import random # Open a file. myfile = open('numbers.txt', 'w') # Write 100 random numbers to the file. for count in range(100): number = random.randint(1,100) myfile.write(str(number) + '\n') # Close the file. myfile.close() print('Done')
e683f0cf6706dbe6aae9b300e94d4cf531467f62
twbot/Random_Python_Files
/hackrank.py
638
3.703125
4
#!/usr/bin/python import sys """def main(): L = [] for x in range(int(raw_input())): s = raw_input().split() if s[0] == 'insert': L.insert(s[1], s[2]) elif s[0] == 'print': print L elif s[0] == 'remove': L.remove(s[1]) elif s[0] == 'append': L.append(s[1])...
e451f375860076dc1ad8ae9f39ae96abc3b0f667
m1ckey/cryptopals
/lib/bit.py
1,990
3.5
4
def xor(b0, b1): """ xor, if one is shorter it is repeated :param b0: bytes :param b1: bytes :return: xor'ed bytes """ length = len(b0) if len(b0) >= len(b1) else len(b1) output = bytearray(length) for i in range(length): output[i] = b0[i % len(b0)] ^ b1[i % len(b1)] r...
af32d314c5f1119b45cc1623f66db61bf17f766e
Linkin-1995/test_code1
/day03/exercise04.py
305
3.84375
4
# 练习: # 在终端中获取一个性别 # 如果是男,提示您好,先生。否则如果是女,提示您好,女士。否则提示性别未知. sex = input("请输入性别:") if sex == "男": print("您好,先生") elif sex == "女": print("您好,女士") else: print("性别未知")
3698dba818e41ae1674a857e274f252619c037d3
saikiranreddygangidi/Apriori_datamining
/sample_apriori.py
957
3.5
4
import pandas as pd import numpy as np from apyori import apriori data = pd.read_excel('path_of_excel_file') df=pd.DataFrame(np.array(data),columns=['list_of_column_names']) records = [] shape=df.shape() for i in range(0, shape[0]): records.append([str(data.values[i,j]) for j in range(0, shape[1])]) print(reco...
7e4174de64cc55727cf64e6fd254dc7c47174cc0
madeibao/PythonAlgorithm
/py根据数字来分割链表.py
984
3.671875
4
# leetcode 86 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def partition(self, head: ListNode, x: int) -> ListNode: # 创建了两个虚拟的节点值。 dummy1 = ListNode(-1) dummy2 = ListNode(-1) p1 = dummy1 ...
a1c0e5d021b49782a5980423518fd0d326d3b7ad
elguerandrea/CS241
/checkpoints/check05b/check05b.py
1,161
3.671875
4
""" CS 241 Checkpoint 5B Written by Chad Macbeth """ """ File: check05b.py Author: Br. Burton Use this file to practice debugging in PyCharm. """ class Money: """ Holds a dollars and cents value. """ def __init__(self, dollars = 0, cents = 0): self.dollars = dollars self.cents = cents ...
cadf4cb0e15ef5bb84b1f5d4f696a1a43c4a7f54
FeiZhan/Algo-Collection
/answers/leetcode/Simplify Path/Simplify Path.py
648
3.609375
4
class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ path_list = [] prev = 0 for i in range(len(path) + 1): if len(path) == i or '/' == path[i]: if prev + 2 == i and '.' == path[i - 2] and '.' =...
01c3c16084eaf7979b36d092087a803c5d1db3e4
brunodantas/coding-questions
/subsequence.py
1,268
3.59375
4
# https://techdevguide.withgoogle.com/resources/find-longest-word-in-dictionary-that-subsequence-of-given-string def init_pdict(words): pdict = dict() for w in words: prefix = w[1][0] if prefix not in pdict: pdict[prefix] = [w] else: pdict[prefix].append(w) r...
29395f5eb4a7c631a23449e5eda020051cc2c321
Candlemancer/Junior-Year
/CS 3430 - Python and Perl/Class Practice/Strings and Operators.py
1,397
4.125
4
# Jonathan Petersen # A01236750 # Strings and Operators # Operators x = 56; y = 80; print(x + y); print(x - y); print(x * y); print(x ** y); print(x / y); print(x // y); print(x % y); x, y = 34, 66; # ^x ^y x, y = y, x; # Swap # Strings firstName = "Gerard"; lastName = "Umulat"; #Similar to printf. Use a % ...
cc42c5936af0d80b80ca43fcfe99852a3a2f6ed9
Ironjanowar/Python
/TalkingBot/talking_bot.py
1,923
3.65625
4
import random #./talkingLib.txt leFile = open("talkingLib.txt") txt = leFile.readlines() '''def selectRandomLine(filerino): num = random.randint(0, 10) while num < 5: filerino.readline() leString = filerino.readline() return leString''' def init_bot(respuestas): while 1: inp = input('>').low...
d3b289dd484be51c0efaa46fc517963ee6a2aa4d
arthur-e/suntransit
/suntransit/__init__.py
8,008
3.71875
4
''' Module for calculating sunrise and sunset times and, more importantly, for the length of a day (in hours). The core algorithm is `sunrise_sunset()`. ''' import datetime import numpy as np # The sunrise_sunset() algorithm was written for degrees, not radians _sine = lambda x: np.sin(np.deg2rad(x)) _cosine = lambda...
a9a7fc6b9fef95134ad61ed411c16ce752a374ed
kaichunchou/Python-Review
/Exercise_14/Exercise_14.py
1,241
4.15625
4
''' Exercise 14 Write a program (function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates. Extras: - Write two different functions to do this - one using a loop and constructing a list, and another using sets. - Go back and do Exercise 5 using sets...
308053e5783335869c16f294849509a733d1b14f
vpc20/leetcode-may-2020
/CourseSchedule.py
3,377
3.96875
4
# There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. Some courses may # have prerequisites, for example to take course 0 you have to first take course 1, which is expressed # as a pair: [0, 1] # # Given the total number of courses and a list of prerequisite pairs, is it possible...
8c9fdb8152729becc92d04ef62dfdacd14d5e37d
kushinoyuya/Python_Project
/05_lesson.py
824
3.59375
4
print("##########演習5-1##########") def display_investory(investory): print('持ち物リスト:') item_total = 0 for k,v in investory.items(): print(str(investory[k])+ ' ' + k) item_total += v print("アイテム総数:" + str(item_total)) stuff = {'ロープ':1, 'たいまつ':6, '金貨':42, '手裏剣':1, '矢':12} display_investory...
2917024d4e1ae8208ac9d7c17e3faaf3c637455a
shjang1013/Algorithm
/BAEKJOON/큐, 덱/18258_큐2.py
1,240
3.65625
4
# queue.pop(0)에서 시간초과 import sys N = int(input()) queue = [] for _ in range(N): command = sys.stdin.readline().split() if command[0] == 'push': queue.append(command[1]) elif command[0] == 'pop': print(queue.pop(0)) if len(queue) else print("-1") elif command[0] == "size": ...
c448ba82dc784564e4da2a1c014475ca8f006509
oneInsect/simple_automl
/server/feature_select/ts_feature_select.py
2,020
3.5625
4
""" CreateTime : 2019/6/3 19:43 Author : X Filename : ts_feature_select.py """ from tsfresh.feature_selection import select_features def feature_selector(X, y, ml_task='auto', n_jobs=0): """ Calculate the relevance table for the features contained in feature matrix `X` with respect to target ve...
ec6bd1821c015bbcadcdf35fb02471c5d5d648ca
seNpAi-code/My_first_pythonProgram
/first.py
338
3.90625
4
# My_first_pythonProgram #my first python program myName="Allen" myAge="19" print("My name is " + myName + ".") print("I'm " + myAge + " years old.") title="Naruto Shippuden" print(title+ " is my favourite anime") playerName="Auspiousjester69" print("My gaming handle is " +playerName) print(playerName.lower()...
39e395ffa92e4540902fc4acbaed691b34a8c0af
lonsty/online-programing
/remove_chars_appear_least.py
759
3.765625
4
# Author: Allen # Date: 2020-4-15 22:47:55 """ 实现删除字符串中出现次数最少的字符,若多个字符出现次数一样,则都 删除。输出删除这些单词后的字符串,字符串中其它字符保持原来的顺序。 注意每个输入文件有多组输入,即多个字符串用回车隔开 """ def remove_least_chars(string): counter = {} for c in string: if c not in counter: counter[c] = 1 else: counter[c] += 1 ...
ff3cf0ab81f18d51dd1b02e8942164bb9cb8e54a
dalexach/holbertonschool-machine_learning
/supervised_learning/0x03-optimization/5-momentum.py
699
4
4
#!/usr/bin/env python3 """ Momentum """ import numpy as np def update_variables_momentum(alpha, beta1, var, grad, v): """ Function that updates a variable using the gradient descent with momentum optimization algorithm: Arguments: - alpha is the learning rate - beta1 is the momentum weight...
f8bb056e12192479ab92907394f9f1426fc4b66f
KimEklund13/SeleniumWD-with-Python3x
/basicsSyntax/methods_homework.py
1,399
4.34375
4
""" Tax in US based on states: Create a method, which takes the state and gross income as arguments and returns the net income after deducting tax based on the state. Assume federal tax: 10% Assume state tax of your residence You don't have to do this for all states, just take 3-4 to solve the purpose of the exercis...
0697bc29e182d04ba41f2051893d55e8ee4bea90
NamanJain14101999/DSA_USING_PYTHON
/TREES_WITH_PYTHON/BST_IN_PYTHON.py
2,642
3.84375
4
class BinarySearchTreeNode: def __init__(self,data): self.data=data self.left=None self.right=None def add_child(self,data): if data == self.data: return if data<self.data: if self.left: self.left.add_child(data) else:...
3dbc5e8594bd733f9600fd0cea409201feb7707c
yangyang5214/note
/bricks/1725.py
518
3.625
4
# -*- coding: utf-8 -*- from typing import List def countGoodRectangles(rectangles: List[List[int]]) -> int: m = {} max_flag = 0 for _ in rectangles: side = min(_[0], _[1]) max_flag = max(max_flag, side) if side in m: m[side] = m[side] + 1 else: m[si...
5b1c98568a19e5add88017b6c8c08bdf9e7339f2
CheungChan/tensorflowtest
/chapter3/chapter3_2.py
1,000
3.734375
4
import tensorflow as tf """ 通过TensorFlow训练神经网络模型 """ w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1)) w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1)) # tf.assign(w1, w2, validate_shape=False) # x = tf.constant([[0.7, 0.9]]) # 定义placeholder作为存放输入数据的地方。这里维度也不一定要定义。但如果维度是确定的,那么给出维度可以降低出错...
b2bd7d6eedbb0de1c6116268ebdd6a1afdbb8bea
mr-sige/user-test
/python/clock.py
142
3.5
4
from datetime import datetime today = datetime.now().strftime("%B %d, %Y") time = datetime.now().time().strftime("%H:%M") print(today, time)
e877703bdc155faf21fb8da6da8cef0ed7791eae
romersjesusds/trabajo
/verificador nro 03.py
451
3.890625
4
#CALCULADORA nro3 # Esta calculadora realiza el calculo del Trabajo en Newton*metro # Declaracion de la variable fuerza2,distancia,trabajo=0.0,0.0,0.0 # Calculadora fuerza2=10 distancia=20 trabajo=fuerza2*distancia #mostrar datos print("fuerza2 = ", fuerza2) print("distancia = ", distancia) print("trab...
768b32fc8fc571afe7820cc46aeb1e034daf20bf
DarkAlexWang/leetcode
/ReferenceSolution/821.shortest-distance-to-a-character.151072700.ac.py
1,083
3.828125
4
# # [841] Shortest Distance to a Character # # https://leetcode.com/problems/shortest-distance-to-a-character/description/ # # algorithms # Easy (62.90%) # Total Accepted: 6.7K # Total Submissions: 10.7K # Testcase Example: '"loveleetcode"\n"e"' # # Given a string S and a character C, return an array of integers re...
9bd48cf83830ca838da07d405e2370c1b61bb71e
ReeceBank/DemandPagingAlgorithms
/paging.py
6,822
3.96875
4
#by Reece van der Bank # writen in python 3.6.4 # FIFO, LRU, and OPT paging algorithms in python. #----- IMPORTS ------------------------------------------------------------------------------------------ import sys import random #----- MAIN (just for the sequence and calls each function) -----------------...
e86d73fb62f51f9a6429c746010eb5b90fe9a3ff
Mandhularajitha/function
/calculater function.py
337
3.734375
4
def add(n1,n2): x1=n1+n2 return x1 def sub(n1,n2): x2=n1-n2 return x2 def mul(n1,n2): x3=n1*n2 return x3 def div(n1,n2): x4=n1%n2 return x4 def fname(a,b): print(add(a,b)) print(sub(a,b)) print(mul(a,b)) print(div(a,b)) n1=int(input("enter num")) n2=int(input("enter num"...
78c5de6539b5e7542352bb92d9fa315584d14d6c
kimanhta87/KimAnhTa-D4E17
/session3/list_intro.py
1,258
3.8125
4
# quan_ao1 = 'hoodie' # quan_ao2 = 'ao phong' # quan_ao3 = 'quan bo' # list_quan_ao = ['hoodie', 'ao phong', ' quan bo',] # print(list_quan_ao) # print(list_quan_ao[-1]) # list_quan_ao.append('ao ba lo') #create # print(list_quan_ao) # list_quan_ao[2] = 'ao bo' #update # index = list_quan_ao('quan que') # ...
937877172d3a8cbde02040ba9bccfa24d93b1cd1
sunil2982/python_core
/turtleChall.py
515
4.28125
4
import turtle obj=turtle.Turtle() sides = int(input("how many sides of polygone you want to drow")) print("do you want to drow polygone into polygone?") ans=input("yes or no?") if ans.upper() == "YES" : for steps in range(sides): obj.forward(100) obj.right(360/sides) for steps in range(...
ca29fe835136990e4bdc6020f6bd610a5a186065
RomanAkhmedov/Python_basics
/lesson_1/task_04.py
594
4.25
4
# Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл # while и другие арифметические операции. user_number = int(input('Введите целое положительное число: ')) max_digit = user_number % 10 while user_number > 0: if user_number % 10 > max_digit: ma...
51ae517c955efb334309e52c22225efe08330761
namankitarana/SSW-555-GEDCOM-Project
/MK_Project03_Siddhart.py
12,610
3.625
4
""" ============================================================================= | Assignment: Project 3 | Author: Siddhart Lapsiwala (slapsiwa@stevens.edu) | Grader: James Rowland | Course: SW555 - Agile Methods of Software Dev. | Instructor: James Rowland | Due Date: Wedn...
a99fb376527ede447e50f2937903fd084eb1c36f
rohitprofessional/test
/CHAPTER 08/nested dict.py
770
4.34375
4
#---------NESTED DICTIONARY--------------- # Dictionary keys having another dictionary in them as values. course = { 'python':{'duration':'3 months','fees':6500}, 'php':{'duration':'2 months','fees':5000}, 'java':{'duration':'3 months','fees':6500}, 'machine learning':{'duration':'2 months','fees':7000}, 'art...
07a2725c3b70b1ec74a3624c972bc853d008fd63
cragworks/python_sockets
/chattyc.py
1,284
3.609375
4
import tkinter as tk from tkinter import * import socket # Import socket module import select root = tk.Tk() T = tk.Text(root, height=20, width = 50, state = NORMAL) T.pack(side=TOP) T2 = tk.Text(root, height=1, width=50) T2.pack(side=LEFT) T2.insert(tk.END, "") def buttonclick(): ta...
d5e70c8eba43bb6c10ede574f9bb20416f421dc7
redashu/pywinter2019
/file_ops.py
353
3.953125
4
#!/usr/bin/python3 import sys # to create a empty files file_names=sys.argv[1:] for i in file_names: f=open(i,'w') # f.write("hello world") f.close() # alternate way for i in file_names: with open(i,'w') as f: f.write("hey python \n") # like appending in a file with open("aa.txt",'a') as f: f.wri...
e00e02ecd3f087eab977d0808f0fdb325839a8c1
EddyATorresC/read_numbers
/image_server/Neural_Network_Testores_to_run.py
4,172
3.515625
4
import numpy as np import scipy as sc from matplotlib import pyplot as plt import pandas as pd import time from IPython.display import clear_output import cv2 re_train = True #Funciones y clases #Capa neuronal class neural_layer(): def __init__(self, n_conn, n_neur): self.b = np.random.rand(1,n_neur) * 2 -1 ...
84cc6b69d6b4d278224c8bff3442df0f4d294723
romeo-25-04/hellion_tools
/src/systems.py
793
3.765625
4
from src.orbit import Coordinates import json """ name is what u see on the map """ class SpaceObject: def __init__(self, name, coordinates=Coordinates()): self.name = name self.coordinates = coordinates self.objects = {} def add_object(self, obj): self.objects[obj.name] = obj...
3f900fe35b7b4ce10df34976ffbbe1a15d58e3ac
AgamalARM/python
/ToggleGUI.py
989
3.75
4
################################################## ### Author : Ahmed Gama #### ### Description : Toggle Function GUI #### ### #### ### Date : 6 Dec 2020 #### ### Version : v1 #### ########...
7d380d70b43c850dc66a31568537c6956d90570d
Gabriel716/Term-1-End
/Python code/python calculator.py
2,434
3.984375
4
#Gabriel Harrison #10/3/2018 #python password #get user input and check for errors def get_input(message): var_value=input(message) return var_value def get_int_input(message): var_value=input(message) if var_value.isdigit(): var_value=int(var_value) return var_v...
8e104bf35367b6150fa4256e4468c841424d58b6
wang55www/pythonStudy
/section8/8_3_7_3.py
484
3.65625
4
#coding:utf-8 class FruitShop(object): "水果商店" def __init__(self,fruits=[]): self.fruits=fruits def __getitem__(self,item): return self.fruits[item] def __str__(self): return self.__doc__ def __call__(self): #对象可以看成一个函数来调用 print("FruitShop call") if __name__ ==...