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
029929a9ebd451c4ef76e7c5da370f1e0552894d
TeamOsKaras/lista3
/Questao10.py
279
3.640625
4
def Questao10_Lista3(Lim_Superior, Lim_Inferior): if Lim_Superior>Lim_Inferior: maior, menor = Lim_Superior, Lim_Inferior else: menor, maior = Lim_Superior, Lim_Inferior for i in range(menor+1, maior): if i%2!=0: print i,
efc99c9fb6d0d705878e1abed8395177e0616fb5
shahmohamadi/IntermediateAdvancedPythonExamples
/IntermediateAdvancedPythonExamples/OOP2.py
623
3.96875
4
# inheritance and destructors class Computer: count = 0 def __init__(self, ram, hard, cpu): self.ram = ram self.hard = hard self.cpu = cpu Computer.count += 1 def value(self): return (self.ram + self.hard + self.cpu) * 100 def __del__(self): Computer.co...
df3b1b911ee16292a1cf94b1c9523c4b0ee2698a
Himanshuhub/Python
/python_fundamentals/Assignment-MultiplesSumAverage.py
299
4.15625
4
# Assignment: Multiples, Sum, Average # Multiples # Part 1 # for count in range(1,1000,2): # print count # Part 2 # for count in range(5,1000005, 5): # print count # Sum List list = [1, 2, 5, 10, 255, 3] print sum(list) # Average List a = [1, 2, 5, 10, 255, 3] print sum(a)/len(a)
99761ef722552da9fe82d3b17e1c32a20737cc92
Himanshuhub/Python
/python_fundamentals/Assignment-FilterbyType.py
845
3.546875
4
# Integer def FilterByType(arg): if isinstance(arg, int): if arg >= 100: print "that's a big number" else: print "That's a small number" elif isinstance(arg, str): if len(arg) >= 50: print "Long sentence" else: print "Short sentenc...
2957eb97c2441ee4b5628e1883e56cbb17d4d274
Himanshuhub/Python
/python_fundamentals/Assignment-Names.py
1,150
3.671875
4
# Assignment: Names # # Part 1 students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def part1(l): for i in l: # print i print i['f...
6ebc94beadb21416b9c2405193ae5b99d8bdf132
mhamdalla/CS5590-APS--PYTHON-PROGRAMMING-LAB1
/LAB1_P3.py
6,602
3.640625
4
import sys import pandas as pd from openpyxl import load_workbook class Book: def __init__(self,listofbooks):#this init method is the first method to be invoked when you create an object #what attributes does a library in general have? - for now, let's abstract and just say it has available...
68856c89e54a1ba0dabf422490a33c7eaab968fe
CoderDream/Algorithmic-Trading-Tutorial
/01. Programs/Tutorial 04 US - Get intraday.py
1,720
3.5
4
import requests import pandas import io import datetime import os import time def dataframeFromUrl(url): dataString = requests.get(url).content parsedResult = pandas.read_csv(io.StringIO(dataString.decode('utf-8')), index_col=0) return parsedResult def stockPriceIntraday(ticker, folder): # Step 1. G...
093054575a8e6ffa31df1e71ad04fdf137d3187a
Slov01/Game
/Game5.py
6,047
3.75
4
import random import plotly import numpy as np import plotly.graph_objects as go from tabulate import tabulate # Set a tuple of resource names. Indexing starts from 0 tuple_resources = ( "Wood", "Stone", "Coal", "Iron", "Komputers", "Planes", "Zoobium", "Victory Points" ) # Set initial commodities ...
b8746222cad3c02c31536986a9f7cce3ccffae53
paudefclasspy/Password-Cracker
/CrackPassword.py
1,311
3.78125
4
import time import string maxattempts = 100000 start = time.time() chars = list(string.printable)[:95] base = len(chars) n = 0 solved = False password = input("Enter your password:") print(chars) # converts number N base 10 to a list of digits base b def numberToB...
11d95f94377f889dae7675eaa47d55b7178c8b3c
fatima-a-khan/ITM200-IntroToProgramming
/poly1.py
581
3.578125
4
#poly.py #Author: Fatima Khan #Input s = input("Enter input such as a=10, b=5, c=1, x=1: \n"); s = s.lower(); #Parse operands i1 = s.find('a'); i2 = s.find(','); ai = s[i1+2:i2].strip(); a = float(ai); o1 = s.find('b'); o2 = s.find(',', i2+1); bo = s[o1+2:o2].strip(); b = float(bo); p1 = s.find('c'); p2 = s.find(',...
bc32d47ddb7e0a444ee9b5d16c11e7d9f5969773
LucyRebecca/PyCharacter
/Character_creation.py
25,488
3.765625
4
import random # declaring globals global size global speed global languages def main(): #will do the creation here print("Hello, welcome to py-character, the python stat rolling simulator!") char_name = input("First, what is your character's name?\n") while True: species = input("Next, what is your ...
13891fd6ce2bd04cbae5c4515b6c9cd004aee04e
mojmir/3d_ttt
/interface/field.py
4,622
3.921875
4
from interface.point import Point import random import constants class Field(object): """ Represents playing field. Attributes: matrix: 3D list of points representing stones full: boolean, is matrix full filled solved: there is already winner Methods: add_stone: add st...
fce714eb12d2b9f2636af075ee60f0e128a0a88f
davidozhang/codeforces
/sinking_ship.py
509
3.8125
4
#!/usr/bin/python ''' Problem 63A: http://codeforces.com/problemset/problem/63/A Solved on: 2015-02-16 Result: Accepted 92 ms 8 KB ''' def main(): order=['rat','woman/child','man','captain'] result={} n=int(raw_input()) for i in range(0, n): name, pos=raw_input().split() if pos=='woman' or pos=='child': po...
a1620a8b53b6cb5d5ae5252e4044fb4418e08fde
davidozhang/codeforces
/string_comparison.py
291
3.609375
4
#!/usr/bin/python ''' Problem 112A: http://codeforces.com/problemset/problem/112/A Solved on: 2015-02-08 Result: Accepted 124 ms 4 KB ''' def main(): a=raw_input().lower() b=raw_input().lower() if a<b: print -1 elif a==b: print 0 else: print 1 if __name__=='__main__': main()
86efe84fe9b649806db7dbb6e2f7d7c7927447f0
davidozhang/codeforces
/haiku.py
593
3.578125
4
#!/usr/bin/python ''' Problem 78A: http://codeforces.com/problemset/problem/78/A Solved on: 2015-02-17 Result: Accepted 92 ms 4 KB ''' def main(): success=True for i in range(0,3): _dict={} _input=''.join(raw_input().split()) for j in _input: if j not in _dict: _dict[j]=1 else: _dict[j]+=1 vow...
87ddd4ee7f2bb33177362c2fd6733728daea7ad7
davidozhang/codeforces
/strings_of_power.py
309
3.5
4
#!/usr/bin/python ''' Problem 318B: http://codeforces.com/problemset/problem/318/B Solved on: 2015-03-05 Result: Accepted 248 ms 5604 KB ''' def main(): result, lst = 0, raw_input().split('heavy') for i in range(len(lst)): result+=lst[i].count('metal')*i print result if __name__=='__main__': main()
a519c83825fb409ff723a114a6a6b3095e612fcc
davidozhang/codeforces
/changing_handles.py
427
3.546875
4
#!/usr/bin/python ''' Problem 501B: http://codeforces.com/problemset/problem/501/B Solved on: 2015-02-23 Result: Accepted 61 ms 200 KB ''' def main(): old, _dict=[], {} for _ in range(int(raw_input())): a,b=raw_input().split() _dict[a]=b if a not in _dict.values(): old.append(a) print len(old) for i in o...
b711cb64f4762919774c5d28911bcb3a41022ead
davidozhang/codeforces
/life_without_zeroes.py
368
3.6875
4
#!/usr/bin/python ''' Problem 75A: http://codeforces.com/problemset/problem/75/A Solved on: 2015-03-08 Result: Accepted 92 ms 8 KB ''' def main(): first, second=raw_input(), raw_input() if (int(str(int(first)+int(second)).replace('0','')))==int(first.replace('0',''))+int(second.replace('0','')): print 'YES' else...
0c97ba83e13193a89f43ed23392414fdaafbdc78
BonaFei/HelloWorld
/compare.py
486
4.03125
4
#!/usr/bin/env python lucky_number = 7 while True: try: input_number = int(input("Please enter a number to guess: ")) except Exception: print("Please input a number") continue if input_number == lucky_number: print("Bingo") break elif input_number < lucky_number...
cb8528a421bfa8c925c6ed74f4906a72f6527742
ghogarerohan/Tic-Tac-Toe-Game-in-Python
/Tic-Tac-Toe.py
4,232
4.09375
4
# -*- coding: utf-8 -*- """ Created on Sat Aug 29 21:14:05 2020 @author: RGhogare """ import random # Creating Board of 3 by 3 def display_board(board): print('\n' * 100) print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') p...
74de87ffb1430aa91764d7cf69e64ca8dc880b35
simarpreet96/python_basic
/Python/SI.py
373
3.953125
4
P = 1 R = 1 T = 1 # Calculates simple interest SI = (P * R * T) / 100 # Print the resultant value of SI print("simple interest is", SI) # This code is contributed by Azkia Anam. pr = input("enter principle amount:") ra = input("enter rate:") ti = input("enter time period:") si = float(pr) * float(ra) * float(...
7e6f3eabd155f459995bb222675dfcc1ccdecd87
simarpreet96/python_basic
/Python/compound.py
437
3.859375
4
def compound_interest(principle, rate, time): # Calculates compound interest CI = principle * (pow((1 + rate / 100), time)) print("Compound interest is", CI) # Driver Code compound_interest(10000, 10.25, 5) pr = input("enter principle amount:") ra = input("enter rate:") ti = input("enter time...
870431cc7b272fda306c071c21690b2a7927551f
Bladefidz/artificial-intelligence
/edx/colombiaX/search-algorithm/inversions.py
669
3.75
4
import sys import math import itertools def inversion(l): n = len(l) inv = 0 for i in range(0, n): for j in range(i, n): if (l[i] > l[j]): inv += 1 return inv def invPermt(n): ''' Print inversions of all possible permutations. ''' for p in itertools.permutations(list(range(1, n + 1))): print("{} ...
e9ad424199d19190bcb6bf2b1fe7d8af7774ccf7
eibon/Pruebas_Python
/rename.py
1,260
3.625
4
print ("hola este programa es para crear listas para un archivo bat encargado de renombrar una lista de archivos") archivo_origen =input("proporcione el nombre del archivo origen ejemplo '2478'") tipoarchivoorigen=input("indique el tipo de archivo ejempleo 'MP4' en caso de no tener tipo poner '*'") numerodarchivos =...
d6cb53ddf684a771262e2f1aa96497c08d1ab7cf
zedaoxd/desvio_padrao
/desvio_padrao.py
718
3.78125
4
# calculando o desvio padrão lista = [] while True: x = input('Digite um valor ou enter para sair: ') if x == '': break elif x != '': lista.append(int(x)) soma = 0 for valor in lista: soma += valor media = soma / len(lista) elevar = [valor - media for valor in lista] quadrados = [valo...
e949d5dbd800b1d47be7e5e2cf3ab09304527871
GuilhermeFariasn7/infosatc-lp-avaliativo-01
/Exer 14.py
181
4.21875
4
##Questão 14 - converter um ângulo para radianos G = float(input("Digite um ângulo em graus: ")) R = ((G * 3.14)/180) print("O angulo {} em radianos ficarah: {:.4f}".format(G,R))
6f78f702a76f2023828206cf56d5e97877206a25
GuilhermeFariasn7/infosatc-lp-avaliativo-01
/Questao 4.py
958
3.671875
4
""" Um determinado prêmio de loteria saiu para um bolão de três amigos. Uma lei garante que todo prêmio de loteria deva pagar um imposto de 7% para os cofres estaduais. Do total descontado o imposto, os amigos irão dividir o prêmio da seguinte maneira: O primeiro ganhador recebera 46%; O segundo recebera 32%; O terceir...
9eb1e8456b09fc34a2d11c5c41c63d85704cc70c
JoyP7/BasicPythonProjects
/rock_paper_scissors.py
1,408
4.28125
4
from random import randint #create a list of play options t = ["Rock", "Paper", "Scissors"] #assign a random play to the computer computer = t[randint(0,2)] #set player to False player = False p_score = 0 c_score = 0 #here is the game while player == False: #case of Tie player = input("Rock, Paper, or Sciss...
846b78b8ffd27189f024f280c2eea0f5106bfb18
sammarchesoni/python-challenge
/PyPoll/main1.py
2,037
3.71875
4
import os import csv pollpath = os.path.join('c:Homework 3_Instructions_PyPoll_Resources_election_data.csv') total_votes = 0 candidates = [] poll = [] candidate_votes = [] candidate_percent = [] winner = "" with open(pollpath, 'r') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') header = next(csvread...
6664b7aba5e117c171e44384e48149fc6124f412
voodeng/lpy
/3.if-elif-else.py
1,647
3.96875
4
#!/bin/env python # coding=utf8 # -*- coding: utf8 -*- from __future__ import division #### if-else #### print '#### if-else ####' a = input("a: ") # 12 or 10+2 b = input("b: ") if(a>b): print "max: ", a else: print "max: ", b #### if-elif-else #### print '#### if-elif-else ####' score = raw_inp...
55c7b745fa57932689b95e4a8b1d868784484cfd
RamonBomfim/lab-de-prog2
/exercicios-aula/questao-6.py
428
3.78125
4
estado_civil = input("Informe se você é Solteiro ou Casado: ").lower() salario = float(input("Informe o seu salário: R$ ")) if estado_civil == 'solteiro': imposto = salario * 0.1 print(f"Você deve pagar R$ {imposto} de imposto.") elif estado_civil == 'casado': imposto = salario * 0.09 print(f"Você deve...
fade2121ae67d47fdac35de756b66e8ef4987401
vylion/vylbot
/diceRoller.py
885
3.875
4
#!/usr/bin/env python3 import random def parse_roll(msg): rolls = msg.split(',') if len(rolls) == 1: return " rolled {}: `{}`".format(msg,roll(rolls[0])) else: answer = " rolled: " for r in rolls: answer += "`{}`, ".format(roll(r)) return answer[:-2] def roll(d...
983cd4caa20205e153ce86593ffd42c81857dfe3
StealthyNinja26/Learn_Python
/problem4/pali.py
196
4.25
4
def ispali(a): return a[::-1] x = input ( "Enter string for checking palindrome: ") y = ispali(x) if( y == x): print("String is a palindrome") else: print("String is not a palindrome")
be0bff3ce3355523b72c06526b8953b20718cbe5
isanjit3/Phonebook
/testScripts/testDisplay.py
2,950
3.546875
4
from operator import itemgetter def displayContacts(data, keys, header=None, sort_by_key=None, sort_order_reverse=False): """Takes a list of dictionaries, formats the data, and returns the formatted data as a text table. Required Parameters: data - Data to process (list of dictionaries). (Type: Li...
50ba828a223436914b93a7d4d4421a828405c559
qcqnotfound/Capacitated-Vehicle-Routing-Problem
/code/Solution.py
6,765
3.828125
4
import random import math class Solution: def __init__(self, instance, max_age): # Instance of the problem self.__instance = instance # Solution self.__solution = [] # Fitness of the solution self.__fitness = 0 # Max age solution could have ...
3b87884e03e9708452e54c7f6bda03371d8a6797
josepmc10/Password
/src/password.py
8,652
3.703125
4
import hashlib import multiprocessing import time class Password: """ Class password to obtain the posible password """ def __init__(self, hash, letters=[["a", "e"], ["f", "j"], ["l", "p"], ["q", "u"], ["v", "y"], ["z", "2"], ["3", "6"], ["7", "9"]], fin_pswd="" ...
4613d70aaa7c3f2328540bced654dff86383233d
Snoblomma/Advent-of-Code-2019
/Day 3/Part 2.py
1,605
3.578125
4
import copy def up(steps, current_location, visited_locations): for i in range(steps): current_location[1] += 1 visited_locations.append(copy.deepcopy(current_location)) def right(steps, current_location, visited_locations): for i in range(steps): current_location[0] += 1 visit...
2178a1c6601a7d5482128736c106c335d98f3553
Spongebob233/Udacity-Full-Stack-Development-log-analysis-project
/log_analysis.py
1,214
3.515625
4
import psycopg2 DBNAME = "news" db = psycopg2.connect(dbname=DBNAME) c = db.cursor() def getMostPopularArticles(): c.execute("SELECT * from article_views ORDER BY views DESC LIMIT 3;") return c.fetchall() def getMostPopularAuthors(): c.execute(""" SELECT author_article.name, SUM(article_views.views) AS au...
5ee2bde50b9cf56e40ca8bc146dd6085eba343d5
YunfeiZHAO/leetcode
/old/binary.py
897
4.21875
4
from typing import List def hammingDistance(x: int, y: int) -> int: ''' The Hamming distance between two integers is the number of positions at which the corresponding bits are different. ''' def DtoB(x: int) -> List[int]: L = [0] * 31 i = 0 while x != 0: L[30 - i] ...
d9f36e1c1302026dc343c1d2366b9cc48c22b3ea
YunfeiZHAO/leetcode
/two_pointers/15_3sum.py
1,261
3.640625
4
from typing import * def twoSum(nums, value): complement = set() result = [] n = len(nums) comp = value - nums[0] if comp not in complement: complement.add(comp) for i in range(1,n): if nums[i] not in complement: complement.add(value - nums[i]) else: ...
b0652b6f3148c4213d754423c27d40276ef4baab
ddtriz/Python-Classes-Tutorial
/main.py
1,223
4.375
4
#BASIC KNOWLDEGE ABOUT CLASSES #What is a class? class firstClass():#Determine a class in the code by using [class] name = "" identification = 0 print ("hello") firstClass.name = "John" firstClass.identification = 326536123 #If you print the firstClass you'll get something like <class '__main__.firstCla...
428646348435da82df2aeae0d40d133887c79720
ihokamura/python_machine_learning_notebook
/sample_kernel_pca.py
1,096
3.75
4
""" show sample of how to use kernel PCA transformer """ import matplotlib.pyplot as plt from sklearn.datasets import make_circles, make_moons from sklearn.decomposition import KernelPCA from kernel_pca import RBFKernelPCA from plot_utility import plot_features def main(): # moon-shaped dataset X, y = make_...
367456613e8c7026d0fb3f0b89813a851b486105
ihokamura/python_machine_learning_notebook
/sample_lda.py
1,834
3.640625
4
""" show sample of how to use LDA classifier """ import matplotlib.pyplot as plt import numpy as np from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardSca...
5e586e1599971c4bb6b41f5b36ecccffce059da1
ihokamura/python_machine_learning_notebook
/sample_linear_regression.py
1,927
3.859375
4
""" show sample of how to use LinearRegressionGD and LinearRegressionSGD """ import matplotlib.pyplot as plt import numpy as np from sklearn.preprocessing import StandardScaler from data_utility import HousingData from linear_regression import LinearRegressionGD, LinearRegressionSGD from plot_utility import plot_pred...
076b01a7edc6c5749308f2800a091603ab6f9dd3
ihokamura/python_machine_learning_notebook
/sample_housing_data.py
1,373
3.59375
4
""" show sample of how to use HousingData """ import itertools import matplotlib.pyplot as plt import numpy as np from data_utility import HousingData def plot_housing_data(): features = ['LSTAT', 'INDUS', 'NOX', 'RM'] D = HousingData(features) variables = np.hstack((D.X, D.y[:, np.newaxis])).T lab...
687ee70110607f2101a85542e53926b23ecfd913
ihokamura/python_machine_learning_notebook
/sbs.py
4,095
3.703125
4
""" SBS algorithm """ from itertools import combinations import numpy as np from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split class SBS: """ SBS (sequential backward selection) algorithm # Parameters ----- * estimator : object estimator, whi...
db33e890eb94a7dbd98f006d9d730de73bdb5bbf
ihokamura/python_machine_learning_notebook
/sample_perceptron.py
1,047
4.03125
4
""" show sample of how to use Perceptron """ import matplotlib.pyplot as plt import numpy as np import pandas as pd from perceptron import Perceptron from data_utility import IrisData from plot_utility import plot_decision_regions def plot_update_history(classifier): errors = classifier.errors_ plt.plot(ran...
92d6893a7b1d2d1b925238aa26634ef9d9060786
stugit/CPPLondonUni
/noughts_and_crosses/play_tictactoe.py
994
3.90625
4
import sys import random number_of_games = 10000 moves = { 0: (0, 0), 1: (0, 1), 2: (0, 2), 3: (1, 0), 4: (1, 1), 5: (1, 2), 6: (2, 0), 7: (2, 1), 8: (2, 2), } # generator that plays pseudo random moves def get_next_move(): seen = {} for x in range(9): move = rando...
bf02a793a9a6c557241ae262097650a0d0c128ac
ifubing/ttsx2019
/a0test/22/父类的研究.py
644
3.921875
4
class Father: def __init__(self): self.name = 'father' def run(self): print('father de run') # o = super() o = super(Father, self) o.teach() def one(self): print('father de one') class Mother: def one(self): print('mother de one') class Teacher...
f7f462a0cc00c3d68b8d0a5bd282151eea24fb9a
ECastro10/Assignments
/rock_paper_scissors_looped.py
2,085
4.125
4
#import random and computer signs list import random signchoices = ["rock", "paper", "scissors"] player1_score = 0 comp_score = 0 game = 0 while game < 3: hand1 = input("Enter rock, paper, or scissors Player1 > ").lower() compSign = random.choice(signchoices) print("Computer chooses " + compSign) i...
dd735f7911236c9ef6ea356879286d1abcbcf510
ECastro10/Assignments
/octothorpe.py
271
3.921875
4
user_input = input("please enter in any word > ") new_word = [] number_of_octothorpes = "#" * (len(user_input) - 4) if len(user_input) <= 4: print("#" * len(user_input)) elif len(user_input) >= 5: print(number_of_octothorpes + (user_input[(len(user_input)-4):]))
54bbeddb55cd85d424fcd78ad94ebc22abd0f505
ECastro10/Assignments
/algorithmforlonglist.py
969
3.953125
4
def efficientgenlist(lo,hi): ''' INPUT: the hi and lo numbers in main() USAGE: this will generate a list of only prime numbers OUTPUT: print the list out ''' num_list = [] num_range = range(lo,hi + 1) for i in num_range: if primo(i) == True: num_list.append(i) ...
0a83d4659dec9035cc267b45c4e31a75288b83f3
luolin1994/leetcode
/linked-list/removeNthFromEnd.py
2,146
3.546875
4
# --coding:utf-8 -- # 19 删除链表的倒数第N个节点 # 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。 # 说明:给定的n保证是有效的 # 进阶:尝试使用一次扫描实现 class ListNode: def __init__(self,x): self.val = x self.next = None class Solution: #扫描两次 def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: #第一次扫描,统计链表的长度 ...
5d39c25ee69051a969647ca342038a22d7ab4d8a
luolin1994/leetcode
/findMaxConsecutiveOnes.py
470
3.703125
4
#--coding:utf8-- #485 最大连续1的个数 #给定一个二进制数组,计算其中最大连续1的个数 #注意:输入的数组只包含0和1,其长度为正整数且不超过10000 nums = [1,1,0,1,1,1] # 返回3 def findMaxOnes(nums): temp = 0 j = 0 for i in range(len(nums)): if (nums[i] == 1): j += 1 if (temp<j): temp = j else: j = 0...
446160870fb1071966d72618817a77d609e2a525
luolin1994/leetcode
/linked-list/deleteNode.py
1,024
3.96875
4
# --coding:utf8-- # 237 删除链表中的节点 #请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。 #说明:链表至少包含两个节点。 # 链表中所有节点的值都是唯一的。 # 给定的节点为非末尾节点并且一定是链表中的一个有效节点。 # 不要从你的函数中返回任何结果。 #输入: head = [4,5,1,9], node = 5 #输出: [4,1,9] #解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9. class Node: def __init__(self, x): self.val...
6d6a6227b82642dfa5d86d155a8927c05afed2e7
anna-s-dotcom/python_final
/Tag12/dozent_projekttag2.py
4,470
3.734375
4
import sqlite3 class BlogsDB: def __init__(self, name): self.filename = name+'.db' self.__createDB() def __createDB(self): con = sqlite3.connect(self.filename) c = con.cursor() c.execute('''CREATE TABLE IF NOT EXISTS users(username TEXT PRIMARY KE...
6699d6537b9ff1cf9c377c329ab07f2822bc2b66
anna-s-dotcom/python_final
/Tag03/dozent_A3.py
377
3.578125
4
x = 9 quadX = x**2 print(quadX) sqrtX = x**0.5 print(sqrtX) # Berechne im mehrdimensionalen Raum den Abstand zwischen zwei Punkten. # für [x1, y1], [x2, y2] = ((x1-x2)**2 + (y1 - y2)**2)**0.5 def abstand(a, b): qsum = 0 for i in range(len(a)): qsum += (a[i]-b[i])**2 return qsum*...
bbf9bd0ea2f255eb5919850c712e49e67b8e7666
anna-s-dotcom/python_final
/Tag06/dozent_rek.py
281
3.546875
4
from turtle import * clear() def spirale(x): if x > 10: spirale(x*0.9) forward(x) left(90) def spirale(x): if x <= 10: return else: spirale(x*0.9) forward(x) left(90) spirale(200) done()
a32514da439c29de6c5a503519be26505c20911d
anna-s-dotcom/python_final
/Tag10/dozent_firstdb.py
2,485
3.625
4
import sqlite3 # con = sqlite3.connect('first.db') # # c = con.cursor() # try: # c.execute("CREATE TABLE person(name TEXT, telefon TEXT)") # except: # print('Table already exists') # erstellen einer tabelle in der datenbank # c.execute("""CREATE TABLE IF NOT EXISTS person(name TEXT, telefon TEXT)...
99cbf8fa58b33a6e5a148444bb7414fc0774e877
anna-s-dotcom/python_final
/Tag09/dozent_projekt1.py
2,337
3.59375
4
class Schulklasse: def __init__(self, stufe, lehrer, schueler): self.stufe = stufe self.lehrer = lehrer self.schueler = schueler self.schueler_anzahl = self.anz() # 1) def anz(self): return len(self.schueler) def stufen_test(self): test = Tru...
58faf3c0ad565bd7945db73221e33b3d089b0453
anna-s-dotcom/python_final
/Tag04/a8.py
234
3.828125
4
jahr = int(input("Bitte geben Sie ein Jahr ein:")) if jahr%400 ==0 or (jahr%4 ==0 and jahr%100!=0): print("Das Jahr " + str(jahr) + " ist ein Schaltjahr.") else: print("Das Jahr " + str(jahr) + " ist kein Schaltjahr.")
1432bcab9faa357c76e538108162711cc296a9aa
Charlesyyun/leetcode
/剑指 Offer 28. 对称的二叉树.py
1,570
4.1875
4
''' 剑指 Offer 28. 对称的二叉树 请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。     1    / \   2   2  / \ / \ 3  4 4  3 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:     1    / \   2   2    \   \    3    3   示例 1: 输入:root = [1,2,2,3,4,4,3] 输出:true 示例 2: 输入:root = [1,2,2,n...
86a8f76a2c9bb6829d9fede0cedb5b467d711124
Charlesyyun/leetcode
/剑指 Offer 25. 合并两个排序的链表.py
1,921
3.84375
4
''' 剑指 Offer 25. 合并两个排序的链表 输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。 示例1: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 限制: 0 <= 链表长度 <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' # Definition for singly-linked ...
3ce58c3246b8addd3d2a561bb940bad5de61b9c0
Charlesyyun/leetcode
/剑指 Offer 13. 机器人的运动范围.py
2,374
3.765625
4
''' 剑指 Offer 13. 机器人的运动范围 地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?   示例 1: 输入:m = 2, n = 3, k = 1 输出:3 示例 2: 输入:m = 3, n = 1, k = 0 输出:1 提...
e58ac31e61fa7f4ddc17e14094bafc3030ba056d
Charlesyyun/leetcode
/剑指 Offer 11. 旋转数组的最小数字.py
3,132
3.875
4
''' 剑指 Offer 11. 旋转数组的最小数字 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。   示例 1: 输入:[3,4,5,1,2] 输出:1 示例 2: 输入:[2,2,2,0,1] 输出:0 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof 著作权归领扣网络所有。商业转载...
062e8ff048613d96cd28727f79157b446e4d78b7
yunnyisgood/Tensorflow
/AE/a01_autoencoder.py
1,888
3.765625
4
''' AutoEncoder : 높은 차원(high-dimensional space)을 낮은 차원(low-dimensional space)으로 변경시키는 과정에서 원본 데이터의 의미 있는 속성들(meaningful properties)을 추출하는 것 ''' from enum import auto import numpy as np from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Model from tensorflow.keras.layers import Dense, Inp...
71edeb55e03f24a95a6ad38ccd15ed7438d1ff06
Raybool/lab_type_sort
/main.py
2,451
3.859375
4
import test as t import random as r def input_len(): # функция ввода длинны массива return int(input("Введите длинну последовательности: ")) def array_sorted_test(col_num): # функция создание сортированного массива a = list() for n in range(0, col_num): a.append(n) return a ...
3f386e9656c8d59fbfa883dbdc039a0089d2a398
katiagilligan888/Algorithms
/stock_prices/stock_prices.py
903
3.984375
4
#!/usr/bin/python import argparse def find_max_profit(arr): if arr.index(max(arr)) > arr.index(min(arr)): return max(arr) - min(arr) else: if(arr[0] and arr[1]): min_value = arr[0] max_profit = arr[1] - arr[0] for price in range(1,len(arr)): if arr[price] < min_value: m...
f7670bf899eaf578b6908741bad3bfb04e9ec308
kasthuri2698/python
/spacepr.py
89
3.765625
4
string=str(input()) count=0 for i in string: if i.isspace(): count+=1 print(count)
052e353f281c0fc814f230eb324d800819688f5e
kasthuri2698/python
/largest.py
129
4.15625
4
int num1 int num2 int num3 if(num1>num2) and (num1>num3): print("num1") elif(num2>num3): print("num2") else: print("num3")
6922ab6a1df517a98324ed90d6e9147cf458066a
kasthuri2698/python
/62p.py
99
3.84375
4
n=input() p=set(n) s={'0','1'} if s==p or s=={'0'} or s=={'1'}: print("yes") else: print("no")
17447f197cb5f09085cca3092957203976273c40
kasthuri2698/python
/pargh.py
99
3.546875
4
str=input() s=len(str) count=1 for i in range(s): if str[i]=='.': count=count+1 print(count)
54b4bd6df361348f9ff7673aa4c343c017c0dcc8
TopalbekirogluMustafa/A-dan-Z-ye-Python-ve-Makine-Ogrenmesi
/Workshops/kacMileEder.py
185
3.5625
4
# -*- coding: utf-8 -*- km =int(input("KM değeri girin: " )) mile = 0.621371192 kacMile = km * mile print (str(km) + " Km olan yolunuz " + str(kacMile) + " Mile Etmektedir.")
f02c96b3f59545fc00f600e61cc9519b50e5267d
lobster87/Building-energy-model
/Create data/Create_Data.py
6,375
3.875
4
import pandas as pd import numpy as np import random import pandas as pd from datetime import datetime def fitnessFunc(population, target): result = abs(population.mean(1) - target) return result """ Import and organise data """ """ Temperature """ temperature_data = pd.read_csv('Temperature data.csv') # Pl...
4b530373651e7765f656810582298c2e56429bf6
malathi777/python-docs-samples
/appengine/standard_python37/hello_world/sum.py
138
3.625
4
def findLen(str): counter = 0 while str[counter:]: counter += 1 return counter str = "geeks" print(findLen(str)
31c2ca34f4aac28348cbd185d20e3e1c239de13b
kamelzcs/study
/divide_two_integers.py
691
3.671875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2014 luxeys <info@luxeys.com> # # Distributed under terms of the MIT license. class Solution: def divide(self, dividend, divisor): def get_bit(dividend, divisor): ans = 0 while (divisor << ans) <= dividend: ans +...
7f84b11bb3515e183a496c1bf8547ad466f615e4
kamelzcs/study
/add_two_numbers.py
3,013
3.703125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2014 luxeys <info@luxeys.com> # # Distributed under terms of the MIT license. import re class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @return a ListNode def addTwoNumbers(...
7b724876e1af2d0ec91dfa3ab08f0adeae726dff
kamelzcs/study
/copylistwithrandom.py
1,255
3.5625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2014 zhao import sys class RandomListNode: def __init__(self, x): self.label = x self.next = None self.random = None class Solution: # @param head, a RandomListNode # @return a RandomListNode def copyRandomList(self,...
f603d6374a5137357110767578e3d05882531d78
kamelzcs/study
/next_right.py
2,925
3.609375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2014 luxeys <info@luxeys.com> # # Distributed under terms of the MIT license. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None self.next = None class Solution: # @param root, a t...
695c5ac1414507b89920128ef98b87aadf843f17
TarunVenkataRamesh-0515/python-515
/setop.py
971
4.15625
4
#set operations set1={1,2,3,4,5,10,12,13} set2={10,11,12,13,14,15,17,19,1} s1={1,2,3,4,5,10,12,13} s2={10,11,12,13,14,15,17,19,1} a={1,2,3,4,5,10,12,13} b={10,11,12,13,14,15,17,19,1} #union()-->All the elements,returns the union as a new set u=set1.union(set2) print("union",u) #union and update """ in update union of ...
5e8670d049b7243e57d117cfb56c0f88a35ba530
robsalzberg/Sprint-Challenge--Computer-Architecture
/cpu.py
6,319
3.515625
4
"""CPU functionality.""" import sys HLT = 0b00000001 LDI = 0b10000010 PRN = 0b01000111 MUL = 0b10100010 POP = 0b01000110 PUSH = 0b01000101 CALL = 0b01010000 RET = 0b00010001 ADD = 0b10100000 CMP = 0b10100111 JMP = 0b01010100 JEQ = 0b01010101 JNE = 0b01010110 class CPU: """Main CPU class.""" def __init__(sel...
10e3c0816fdc2efeaf08ec12ee2606749084b53e
theSekyi/DS-Unit-3-Sprint-1-Software-Engineering
/Sprint-Challenge/acme.py
1,451
3.609375
4
class Product(object): """ A Python Class from which Acme Co. can build specific product instances """ import random ri = random.randint(1000000, 9999999) def __init__(self, name, price=10, weight=20, flammability=0.5, identifier=ri): self.name=name self.price=price self....
52f50c91dafeb505b414ca2ba1031c50ffe57129
mihirkelkar/EPI
/Tree/Binary_Tree_Balanced/balanced.py
342
3.5
4
def checkBalanced(node): if node == None: return -1 left_height = checkBalanced(node.left) if left_height == False: return False right_height = checkBalanced(node.right) if right_height == False: return False if math.abs(left_height - right_height) > 1: return False return max(left_heig...
abdb74d0fa7638c6ab243ed72d51447bbb0c7c32
mihirkelkar/EPI
/Hash/Parition_Into_Anagrams/partIntoAnagrams.py
388
3.765625
4
def partitionIntoAnagrams(array): anagramMap = {} for ii in array: try: anagramMap[''.join(sorted(ii))] += [ii] except: anagramMap[''.join(sorted(ii))] = [ii] #print anagramMap return [string for sublist in anagramMap.values() for string in sublist] array = ['elvis', 'silent', 'debitcard',...
af0b249392e5c8bac633b2ba7b3c7fce62a1b36a
mihirkelkar/EPI
/List_And_Arrays/Indices_To_Sort_Within/indicesToSortWithin.py
640
3.78125
4
def indexToSort(array): ii = 0 jj = len(array) - 1 flag = [0, 0] while ii < jj: if array[ii] <= array[ii + 1]: ii += 1 else: flag[0] = 1 if array[jj - 1] <= array[jj]: jj -= 1 else: flag[1] = 1 if flag == [1, 1]: break if ii < jj: min_middle = min(array[ii...
bc2c1267f222241454be6027e662487fb206eb9e
mihirkelkar/EPI
/Same_Number_On_Rotation/sameNumRot.py
285
3.75
4
def rotateCompare(number): start = 10 while number > 0: newNum = number % start if newNum!=1 and newNum!=8 and newNum!=9 and newNum!=6 and newNum!=0: return False else: number = number // 10 return True print rotateCompare(711) print rotateCompare(161)
b0ed5eac77924b712e5dad6005c4aceb92dbbe36
mihirkelkar/EPI
/List_And_Arrays/Common_Elements_In_Array/int_arrays.py
681
3.953125
4
def common_ints(array_one, array_two): array_one = sorted(array_one) array_two = sorted(array_two) counter_one = 0 counter_two = 0 common_elements = list() while counter_one < len(array_one) and counter_two < len(array_two): if array_one[counter_one] == array_two[counter_two]: common_elements.appe...
4c2edc8b4fd2b164d580bc66539049e928c39710
mihirkelkar/EPI
/Graphs/TopologicalSort/topologySort.py
1,075
3.75
4
from collections import defaultdict class Graph(object): def __init__(self): self.graph_list = defaultdict(list) self.visited = None self.stack = list() def addVertices(self, vertex_list, num): for ii in vertex_list: self.graph_list[ii[0]].append(ii[1]) self.vi...
3832645b997f8d52235c792ad7567224292cd6f6
mihirkelkar/EPI
/List_And_Arrays/Count_Min_Steps_To_Desired_Array/countMinSteps.py
720
3.859375
4
def countMinSteps(target_array): result = 0 zero_count = 0 while zero_count < len(target_array): zero_count = 0 target_array, temp = action(target_array) print target_array, zero_count print "-----------------------" result += temp for ii in target_array: if ii == 0: zero...
9d2738fd3fb4aef054016338c05ede25d772b45a
mihirkelkar/EPI
/Tricky/Count_Frequencies/Pythagorean_Triplets/pythaTriplets.py
459
3.625
4
import math def pythaTriplets(array): array = [ii * ii for ii in array] hashmap = {} for ii in array: hashmap[ii] = 1 sorted_a = sorted(array) for ii in range(len(sorted_a)): for jj in range(ii+1, len(sorted_a)): try: temp = hashmap[sorted_a[ii] + sorted_a[jj]] print (math.sqrt(...
0a99ac1a6103d9405b81b56039a39d7f9c13738f
mihirkelkar/EPI
/List_And_Arrays/Group_Anagrams/groupAnagrams.py
241
3.71875
4
import collections def groupAnagrams(array): word_dict = collections.defaultdict(list) for ii in array: word_dict[''.join(sorted(ii))].append(ii) print word_dict.values() groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"])
db035711169f82776ea7532f4bdf2c749a6aea4d
mihirkelkar/EPI
/Tricky/Jumping_Numbers/jumpingNum.py
512
3.703125
4
def jumpingNums(number): que = list() que += [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] while que: num = que.pop(0) print num if num % 10 == 0: temp = num * 10 + 1 if temp < number: que.append(temp) elif num % 10 == 9: temp = num * 10 + 8 if temp < number: que.append(te...
b107f6cd36bf56cf5725e57076caf1414ce912e0
mihirkelkar/EPI
/Tree/Nodes_Within_Range/nodesInRange.py
441
3.546875
4
class Node(object): def __init__(self, value): self.value=value self.left=None self.right = None def findCount(node, min, max): if node == None: return 0 if node.value >= min and node.value <= max: return 1 + findCount(node.left, min, max) + findCount(node.right, min, max) elif node.value...
e2ee6f667c5ed90bd704b1075f5187f8188aa53a
mihirkelkar/EPI
/List_And_Arrays/Find_Missing_Element/find_missing_element.py
1,189
3.765625
4
def findMissingNumber(array_one, array_two): #This has a O(nLogn) array_one.sort() array_two.sort() print zip(array_one, array_two) for num_one, num_two in zip(array_one, array_two): if num_one != num_two: return num_one return array_one[-1] def findMissing(array_one, array_two): #O(n) time an...
a633b378965af97ece7e4e82062ffbe8a0c11f26
mihirkelkar/EPI
/Tree/Path_Sum/path_sum.py
677
3.84375
4
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None def pathSum(root, count, sum): if root == None: return False else: count += root.value if count == sum: return True elif count < sum: left_h = pathSum(root.left, count, sum...
ed442397ff8af48fc340a6f0fb696ebe7a3c892e
mihirkelkar/EPI
/List_And_Arrays/Shift_by_K/Max_Diff_Two_Elements/max_diff.py
554
3.75
4
def maxDiffNaive(array): max_diff = 0 for ii in range(0, len(array)): for jj in range(ii + 1, len(array)): if array[jj] > array[ii]: if array[jj] - array[ii] > max_diff: max_diff = array[jj] - array[ii] print max_diff def maxDiff(array): min_so_far = array[0] max_diff = 0 for i...
d53ed1e8049ea63c70ef71fe17c7fd1534a6db8a
mihirkelkar/EPI
/Tricky/Deck_Shuffling/deck.py
209
3.515625
4
import random def deck(array): for ii in range(0, len(array)): temp = random.randint(ii, len(array)-1) array[ii], array[temp] = array[temp], array[ii] return array print deck([1, 2, 3, 4, 5])
22f34d973bc41c14f0cbf0c21479277b17d584e2
mihirkelkar/EPI
/List_And_Arrays/Spiral_Matrix_print/spiralMatrix.py
970
3.734375
4
def spiralPrint(matrix): minrow = 0 maxrow = len(matrix) - 1 mincol = 0 maxcol = len(matrix[0]) - 1 row = 0 col = 0 state = 'right' solutions = list() while len(solutions) < len(matrix) * len(matrix[0]): solutions.append(matrix[row][col]) if state == 'right': if col < maxcol: col...
e67060cb4ed4203840992c44d2da61c1f764ebd9
mihirkelkar/EPI
/List_And_Arrays/Copy_Postings_list/postingsList.py
1,372
3.890625
4
def duplicateList(head): if head == None: return None else: current = head while current != None: duplicate = Node(current.value) duplicate.next = current.next current.next = duplicate current = duplicate.next cur = head while cur != None: cur = cur.next return...
d1477f5780c58e0beb51353f4f5e37426b95d67d
PattyDaddy/Control-Flow
/ControlFlow.py
3,394
4.28125
4
name = input("What is your name: ") ## Greeting Function def greeting(): print("Hello there " + name + ".") print("\n***Greetings Function***\n") greeting() # Programmer: PattyDaddy # Date: 12.16.19 # Program: Guess My Number myNumber = 7 print("\nGuess a number between One & Ten\n") # Ask users to guess gues...